You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@velocity.apache.org by cb...@apache.org on 2026/09/15 12:11:26 UTC

(velocity-engine) branch master updated (8eab1e8e -> ae5215e8)

This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/velocity-engine.git


    from 8eab1e8e Deprecate lenient math (only strict match mode supported in next version) - a bit painful because 2.5 will have to ship a deprecated default setting, but rather corner case
     new 9e53f0f1 Deprecate velocimacro.enable_bc_mode without replacement
     new f2a2d7af Deprecate velocimacro library old default name ; warn about deprecation warnings
     new 614ef32d Deprecate mutable integer ranges (runtime.immutable_ranges = false)
     new 0e443a8d Deprecate createNewParser() method ; silent some internal deprecation warnings
     new 514cccbf Update changelog
     new ae068a34 Fix: #evaluate() max depth should honor directive.parse.max_depth
     new 16a69933 Resource loaders now enforce templates paths to stay in their configured root
     new a6f7fc88 SecureUberspector checks Class receivers before static-method lookup
     new ae5215e8 Deprecate parser.class property, as well as DOLLAR char customization

The 9 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 src/changes/changes.xml                            |  29 +++
 .../apache/velocity/runtime/ParserPoolImpl.java    |   1 +
 .../apache/velocity/runtime/RuntimeConstants.java  |  29 ++-
 .../apache/velocity/runtime/RuntimeInstance.java   |  45 +++++
 .../apache/velocity/runtime/RuntimeServices.java   |   2 +
 .../velocity/runtime/VelocimacroFactory.java       |   5 +
 .../velocity/runtime/directive/Evaluate.java       |  32 +++
 .../apache/velocity/runtime/directive/Include.java |   8 +-
 .../runtime/directive/VelocimacroProxy.java        |   1 +
 .../runtime/parser/node/ASTIntegerRange.java       |   1 +
 .../velocity/runtime/parser/node/ASTReference.java |   1 +
 .../resource/loader/ClasspathResourceLoader.java   |   6 +
 .../resource/loader/DataSourceResourceLoader.java  |  13 ++
 .../resource/loader/FileResourceLoader.java        |  54 ++++-
 .../runtime/resource/loader/JarResourceLoader.java |   6 +
 .../runtime/resource/loader/ResourceLoader.java    |  77 +++++++
 .../resource/loader/StringResourceLoader.java      |  13 ++
 .../runtime/resource/loader/URLResourceLoader.java |   6 +
 .../util/introspection/SecureIntrospectorImpl.java |   3 +-
 .../util/introspection/SecureUberspector.java      |  26 +++
 .../velocity/runtime/defaults/velocity.properties  |   4 +
 .../velocity/test/DeprecationWarningTestCase.java  | 221 +++++++++++++++++++++
 .../org/apache/velocity/test/EvaluateTestCase.java |  69 +++++++
 .../test/ResourceNameNormalizationTestCase.java    | 205 +++++++++++++++++++
 .../velocity/test/SecureIntrospectionTestCase.java |  48 +++++
 .../src/test/resources/normalization/outside.txt   |   1 +
 .../src/test/resources/normalization/root/inc.vm   |   1 +
 .../resources/normalization/root/includedown.vm    |   1 +
 .../test/resources/normalization/root/includeup.vm |   1 +
 .../test/resources/normalization/root/parseup.vm   |   1 +
 .../test/resources/normalization/root/sub/inner.vm |   1 +
 31 files changed, 897 insertions(+), 14 deletions(-)
 create mode 100644 velocity-engine-core/src/test/java/org/apache/velocity/test/ResourceNameNormalizationTestCase.java
 create mode 100644 velocity-engine-core/src/test/resources/normalization/outside.txt
 create mode 100644 velocity-engine-core/src/test/resources/normalization/root/inc.vm
 create mode 100644 velocity-engine-core/src/test/resources/normalization/root/includedown.vm
 create mode 100644 velocity-engine-core/src/test/resources/normalization/root/includeup.vm
 create mode 100644 velocity-engine-core/src/test/resources/normalization/root/parseup.vm
 create mode 100644 velocity-engine-core/src/test/resources/normalization/root/sub/inner.vm


(velocity-engine) 04/09: Deprecate createNewParser() method ; silent some internal deprecation warnings

Posted by cb...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/velocity-engine.git

commit 0e443a8d647feab0d5bc5a10b0bc56b09f17545c
Author: Claude Brisson <cl...@renegat.net>
AuthorDate: Mon Sep 14 19:21:04 2026 +0200

    Deprecate createNewParser() method ; silent some internal deprecation warnings
---
 .../src/main/java/org/apache/velocity/runtime/ParserPoolImpl.java       | 1 +
 .../src/main/java/org/apache/velocity/runtime/RuntimeInstance.java      | 2 ++
 .../src/main/java/org/apache/velocity/runtime/RuntimeServices.java      | 2 ++
 .../java/org/apache/velocity/runtime/directive/VelocimacroProxy.java    | 1 +
 .../java/org/apache/velocity/runtime/parser/node/ASTIntegerRange.java   | 1 +
 .../main/java/org/apache/velocity/runtime/parser/node/ASTReference.java | 1 +
 6 files changed, 8 insertions(+)

diff --git a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/ParserPoolImpl.java b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/ParserPoolImpl.java
index 13d8f58f..0503f56f 100644
--- a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/ParserPoolImpl.java
+++ b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/ParserPoolImpl.java
@@ -43,6 +43,7 @@ public class ParserPoolImpl implements ParserPool {
      * @param rsvc
      */
     @Override
+    @SuppressWarnings("deprecation")
     public void initialize(RuntimeServices rsvc)
     {
         log = rsvc.getLog("parser");
diff --git a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeInstance.java b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeInstance.java
index 8e348b36..c82459f1 100644
--- a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeInstance.java
+++ b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeInstance.java
@@ -1323,7 +1323,9 @@ private void initializeParserPool()
      * Returns a JavaCC generated Parser.
      *
      * @return Parser javacc generated parser
+     * @deprecated since 2.5: the next major version has no pluggable parser to hand out.
      */
+    @Deprecated
     @Override
     public Parser createNewParser()
     {
diff --git a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeServices.java b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeServices.java
index eec0e335..26912bdb 100644
--- a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeServices.java
+++ b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeServices.java
@@ -451,7 +451,9 @@ boolean addVelocimacro(String name,
     /**
      * Create a new parser instance.
      * @return A new parser instance.
+     * @deprecated since 2.5: the next major version has no pluggable parser to hand out.
      */
+    @Deprecated
     Parser createNewParser();
 
     /**
diff --git a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/directive/VelocimacroProxy.java b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/directive/VelocimacroProxy.java
index 0aa62ddc..d04641ad 100644
--- a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/directive/VelocimacroProxy.java
+++ b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/directive/VelocimacroProxy.java
@@ -148,6 +148,7 @@ public int getNumArgs()
      * Initialize members of VelocimacroProxy.  called from MacroEntry
      * @param rs runtime services
      */
+    @SuppressWarnings("deprecation")
     public void init(RuntimeServices rs)
     {
         rsvc = rs;
diff --git a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/parser/node/ASTIntegerRange.java b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/parser/node/ASTIntegerRange.java
index 37e95d8b..0091e651 100644
--- a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/parser/node/ASTIntegerRange.java
+++ b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/parser/node/ASTIntegerRange.java
@@ -213,6 +213,7 @@ public int size()
      * @throws MethodInvocationException
      */
     @Override
+    @SuppressWarnings("deprecation")
     public Object value(InternalContextAdapter context)
         throws MethodInvocationException
     {
diff --git a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/parser/node/ASTReference.java b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/parser/node/ASTReference.java
index 37dbe8bb..0c6a7222 100644
--- a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/parser/node/ASTReference.java
+++ b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/parser/node/ASTReference.java
@@ -199,6 +199,7 @@ public void setExtraDollar(boolean extraDollar)
      * @see org.apache.velocity.runtime.parser.node.SimpleNode#init(org.apache.velocity.context.InternalContextAdapter, java.lang.Object)
      */
     @Override
+    @SuppressWarnings("deprecation")
     public Object init(InternalContextAdapter context, Object data)
     throws TemplateInitException
     {


(velocity-engine) 06/09: Fix: #evaluate() max depth should honor directive.parse.max_depth

Posted by cb...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/velocity-engine.git

commit ae068a34891b22da1acf5d79cc82992837d3a7bb
Author: Claude Brisson <cl...@renegat.net>
AuthorDate: Tue Sep 15 11:19:04 2026 +0200

    Fix: #evaluate() max depth should honor directive.parse.max_depth
---
 src/changes/changes.xml                            |  5 ++
 .../apache/velocity/runtime/RuntimeConstants.java  |  6 +-
 .../velocity/runtime/directive/Evaluate.java       | 32 ++++++++++
 .../velocity/runtime/defaults/velocity.properties  |  4 ++
 .../org/apache/velocity/test/EvaluateTestCase.java | 69 ++++++++++++++++++++++
 5 files changed, 115 insertions(+), 1 deletion(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index e47a4db5..59148f9e 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -39,6 +39,11 @@
 
   <body>
     <release version="2.5" date="2026-06-14">
+        <action type="fix" dev="cbrisson">
+            <code>#evaluate</code> now honours the nesting depth limit set by
+            <code>directive.parse.max_depth</code> (10 by default, zero or less meaning no
+            limit).
+        </action>
         <action type="fix" dev="cbrisson" due-to="ogawaffm" issue="VELOCITY-996">
             Fix precision loss when converting <code>Long</code> values to
             <code>BigDecimal</code> in VTL math operations.
diff --git a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeConstants.java b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeConstants.java
index 8cedd936..de25cf41 100644
--- a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeConstants.java
+++ b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeConstants.java
@@ -105,7 +105,11 @@ public interface RuntimeConstants extends DeprecatedRuntimeConstants
      */
     String ERRORMSG_END = "directive.include.output_error_end";
 
-    /** Maximum recursion depth allowed for the #parse directive. */
+    /**
+     * Maximum nesting depth allowed for the #parse and #evaluate directives, which share the
+     * same template name stack: a chain mixing both directives is counted as a whole
+     * (#evaluate honours this limit since 2.5).
+     */
     String PARSE_DIRECTIVE_MAXDEPTH = "directive.parse.max_depth";
 
     /** Maximum recursion depth allowed for the #define directive. */
diff --git a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/directive/Evaluate.java b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/directive/Evaluate.java
index e6c2aa28..b13db11a 100644
--- a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/directive/Evaluate.java
+++ b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/directive/Evaluate.java
@@ -25,6 +25,7 @@
 import org.apache.velocity.exception.ParseErrorException;
 import org.apache.velocity.exception.ResourceNotFoundException;
 import org.apache.velocity.exception.TemplateInitException;
+import org.apache.velocity.runtime.RuntimeConstants;
 import org.apache.velocity.runtime.RuntimeServices;
 import org.apache.velocity.runtime.parser.ParseException;
 import org.apache.velocity.runtime.parser.node.Node;
@@ -39,6 +40,11 @@
 /**
  * Evaluates the directive argument as a VTL string, using the existing
  * context.
+ * <p>
+ * The nesting depth is limited by the <code>directive.parse.max_depth</code> property
+ * (10 by default, zero or less meaning unlimited): <code>#evaluate</code> and
+ * <code>#parse</code> share the same template name stack, so a chain mixing both
+ * directives is counted as a whole against that one limit.
  *
  * @author <a href="mailto:wglass@apache.org">Will Glass-Husain</a>
  * @version $Id$
@@ -46,6 +52,10 @@
  */
 public class Evaluate extends Directive
 {
+    /**
+     * Maximum nesting depth, shared with #parse, zero or less meaning unlimited.
+     */
+    private int maxDepth;
 
     /**
      * Return name of this directive.
@@ -81,6 +91,8 @@ public void init(RuntimeServices rs, InternalContextAdapter context,
     {
         super.init( rs, context, node );
 
+        this.maxDepth = rsvc.getInt(RuntimeConstants.PARSE_DIRECTIVE_MAXDEPTH, 10);
+
         /*
          * Check that there is exactly one argument and it is a string or reference.
          */
@@ -143,6 +155,26 @@ public boolean render(InternalContextAdapter context, Writer writer,
             ParseErrorException, MethodInvocationException
     {
 
+        if (maxDepth > 0)
+        {
+            /*
+             * see if we have exceeded the configured max depth.
+             */
+            String[] templateStack = context.getTemplateNameStack();
+            if (templateStack.length >= maxDepth)
+            {
+                StringBuilder path = new StringBuilder();
+                for (String aTemplateStack : templateStack)
+                {
+                    path.append(" > ").append(aTemplateStack);
+                }
+                log.error("#{}(): max recursion depth reached ({}). File stack: {}",
+                          getName(), maxDepth, path);
+
+                return false;
+            }
+        }
+
         /*
          * Evaluate the string with the current context.  We know there is
          * exactly one argument and it is a string or reference.
diff --git a/velocity-engine-core/src/main/resources/org/apache/velocity/runtime/defaults/velocity.properties b/velocity-engine-core/src/main/resources/org/apache/velocity/runtime/defaults/velocity.properties
index 38cdb51e..a00a05db 100644
--- a/velocity-engine-core/src/main/resources/org/apache/velocity/runtime/defaults/velocity.properties
+++ b/velocity-engine-core/src/main/resources/org/apache/velocity/runtime/defaults/velocity.properties
@@ -49,6 +49,10 @@ directive.if.empty_check = true
 # ----------------------------------------------------------------------------
 # P A R S E  P R O P E R T I E S
 # ----------------------------------------------------------------------------
+# Maximum nesting depth of #parse and #evaluate, which share the same template
+# name stack: a chain mixing both directives is counted as a whole. Zero or
+# less means no limit.
+# ----------------------------------------------------------------------------
 
 directive.parse.max_depth = 10
 
diff --git a/velocity-engine-core/src/test/java/org/apache/velocity/test/EvaluateTestCase.java b/velocity-engine-core/src/test/java/org/apache/velocity/test/EvaluateTestCase.java
index fc5c1d1b..90fa6ef8 100644
--- a/velocity-engine-core/src/test/java/org/apache/velocity/test/EvaluateTestCase.java
+++ b/velocity-engine-core/src/test/java/org/apache/velocity/test/EvaluateTestCase.java
@@ -170,6 +170,75 @@ public void testEventHandler()
     }
 
 
+    /**
+     * Test that a self-referential #evaluate stops at the default depth
+     * instead of recursing until the stack is exhausted.
+     */
+    public void testEvaluateMaxDepthDefault()
+    {
+        context.put("bomb", "X#evaluate($bomb)");
+
+        /*
+         * the limit is 10 by default and the template itself occupies the first
+         * slot of the shared template name stack, hence nine nested evaluations
+         */
+        assertEvalEquals("XXXXXXXXX", "#evaluate($bomb)");
+    }
+
+    /**
+     * Test that the depth limit is configurable and that reaching it is logged.
+     */
+    public void testEvaluateMaxDepthConfigured()
+    {
+        engine.setProperty(RuntimeConstants.PARSE_DIRECTIVE_MAXDEPTH, "3");
+        context.put("bomb", "X#evaluate($bomb)");
+        log.startCapture();
+
+        assertEvalEquals("XX", "#evaluate($bomb)");
+
+        assertTrue("expected the limit to be logged, got: " + log.getLog(),
+                   log.getLog().contains("#evaluate(): max recursion depth reached (3)"));
+    }
+
+    /**
+     * Test that a zero or negative limit means no limit.
+     */
+    public void testEvaluateMaxDepthUnlimited()
+    {
+        engine.setProperty(RuntimeConstants.PARSE_DIRECTIVE_MAXDEPTH, "0");
+        context.put("i", 0);
+        // recursion that stops by itself, deeper than the default limit would allow
+        context.put("rec", "X#set($i = $i + 1)#if($i < 15)#evaluate($rec)#end");
+
+        assertEvalEquals("XXXXXXXXXXXXXXX", "#evaluate($rec)");
+    }
+
+    /**
+     * Test that the limit does not affect an #evaluate which does not recurse.
+     */
+    public void testEvaluateMaxDepthNoRecursion()
+    {
+        // 2 is the lowest limit leaving room for one evaluation, the template being the first
+        engine.setProperty(RuntimeConstants.PARSE_DIRECTIVE_MAXDEPTH, "2");
+        context.put("foo", "bar");
+
+        assertEvalEquals("bar", "#evaluate('$foo')");
+    }
+
+    /**
+     * Test that #parse and #evaluate share the limit, since they share the
+     * template name stack.
+     */
+    public void testEvaluateMaxDepthSharedWithParse()
+    {
+        engine.setProperty(RuntimeConstants.PARSE_DIRECTIVE_MAXDEPTH, "3");
+        addTemplate("shared.vm", "P#evaluate($bomb)");
+        context.put("bomb", "X#evaluate($bomb)");
+
+        // the #parse takes the second slot, so a single nested evaluation is left
+        assertEvalEquals("PX", "#parse('shared.vm')");
+    }
+
     /**
      * Test errors are thrown
      * @throws Exception


(velocity-engine) 02/09: Deprecate velocimacro library old default name ; warn about deprecation warnings

Posted by cb...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/velocity-engine.git

commit f2a2d7af5a73610913086ee32528dce1465ce0ff
Author: Claude Brisson <cl...@renegat.net>
AuthorDate: Sun Sep 13 19:02:18 2026 +0200

    Deprecate velocimacro library old default name ; warn about deprecation warnings
---
 .../apache/velocity/runtime/RuntimeInstance.java   |  2 +
 .../velocity/runtime/VelocimacroFactory.java       |  5 ++
 .../velocity/test/DeprecationWarningTestCase.java  | 68 ++++++++++++++++++++++
 3 files changed, 75 insertions(+)

diff --git a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeInstance.java b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeInstance.java
index 6f025f81..ae8efd59 100644
--- a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeInstance.java
+++ b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeInstance.java
@@ -414,6 +414,8 @@ private void warnDeprecatedSettings()
             return;
         }
 
+        log.warn("deprecation warnings are on; set {} to false to silence them", RUNTIME_DEPRECATION_WARN);
+
         if (hyphenAllowedInIdentifiers)
         {
             log.warn("the '{}' option is deprecated: hyphenated identifiers (e.g. $foo-bar) cannot be expressed in the next major version", PARSER_HYPHEN_ALLOWED);
diff --git a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/VelocimacroFactory.java b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/VelocimacroFactory.java
index b7961a5d..4f694594 100644
--- a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/VelocimacroFactory.java
+++ b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/VelocimacroFactory.java
@@ -163,6 +163,11 @@ public void initVelocimacro()
                      if (rsvc.getLoaderNameForResource(RuntimeConstants.OLD_VM_LIBRARY_DEFAULT) != null)
                      {
                          libfiles = RuntimeConstants.OLD_VM_LIBRARY_DEFAULT;
+                         if (rsvc.getBoolean(RuntimeConstants.RUNTIME_DEPRECATION_WARN, true))
+                         {
+                             log.warn("the macro library was found under its pre-2.1 default name '{}', which the next major version does not search for any more: rename it '{}' or declare it with '{}'",
+                                      RuntimeConstants.OLD_VM_LIBRARY_DEFAULT, RuntimeConstants.VM_LIBRARY_DEFAULT, RuntimeConstants.VM_LIBRARY);
+                         }
                      }
                      else
                      {
diff --git a/velocity-engine-core/src/test/java/org/apache/velocity/test/DeprecationWarningTestCase.java b/velocity-engine-core/src/test/java/org/apache/velocity/test/DeprecationWarningTestCase.java
index 39b278fd..4f45d30f 100644
--- a/velocity-engine-core/src/test/java/org/apache/velocity/test/DeprecationWarningTestCase.java
+++ b/velocity-engine-core/src/test/java/org/apache/velocity/test/DeprecationWarningTestCase.java
@@ -23,6 +23,7 @@
 import org.apache.velocity.exception.MathException;
 import org.apache.velocity.runtime.RuntimeConstants;
 import org.apache.velocity.runtime.resource.loader.StringResourceLoader;
+import org.apache.velocity.runtime.resource.util.StringResourceRepository;
 import org.apache.velocity.test.misc.TestVelocityEngine;
 
 import java.util.Properties;
@@ -38,6 +39,7 @@
  * and the settings the next major version does not provide any more:
  * <ul>
  *   <li>{@code velocimacro.enable_bc_mode}</li>
+ *   <li>an implicitly loaded macro library</li>
  * </ul>
  */
 public class DeprecationWarningTestCase extends BaseTestCase
@@ -486,4 +488,70 @@ public void testBcModeSilentWhenDeprecationOff()
         assertSilentAtInit(RuntimeConstants.VM_ENABLE_BC_MODE, false, RuntimeConstants.VM_ENABLE_BC_MODE, "true");
     }
 
+
+    /* ---- an implicitly loaded macro library: deprecated, declare it instead ---- */
+
+    private static final String OLD_DEFAULT_LIBRARY = "pre-2.1 default name";
+
+    /**
+     * Initializes an engine whose loader can serve a library under the given name, which the engine
+     * then looks for on its own unless a library is declared.
+     *
+     * @param warn value of runtime.deprecation.warn
+     * @param libraryName the name the library is served under
+     * @param declaredPath value of velocimacro.library.path, or null to leave it unset
+     * @return what was logged at init
+     */
+    private String warningsAtInitWithLibrary(boolean warn, String libraryName, String declaredPath)
+    {
+        StringResourceRepository repository = StringResourceLoader.getRepository();
+        repository.putStringResource(libraryName, "#macro(fromlibrary)x#end");
+        try
+        {
+            VelocityEngine ve = settingEngine(warn, RuntimeConstants.VM_LIBRARY, declaredPath);
+            return warningsAtInit(ve);
+        }
+        finally
+        {
+            repository.removeStringResource(libraryName);
+        }
+    }
+
+    public void testOldDefaultMacroLibraryNameWarns()
+    {
+        String out = warningsAtInitWithLibrary(true, RuntimeConstants.OLD_VM_LIBRARY_DEFAULT, null);
+        assertTrue("a library found under the pre-2.1 name must warn, log was:\n" + out,
+                   out.contains(OLD_DEFAULT_LIBRARY) && out.contains(RuntimeConstants.OLD_VM_LIBRARY_DEFAULT));
+        assertTrue("the warning must say how to fix it, log was:\n" + out,
+                   out.contains(RuntimeConstants.VM_LIBRARY_DEFAULT) && out.contains(RuntimeConstants.VM_LIBRARY));
+    }
+
+    public void testDefaultMacroLibraryNameNeverWarns()
+    {
+        // velocimacros.vtl is still searched for in the next major version: nothing to warn about
+        String out = warningsAtInitWithLibrary(true, RuntimeConstants.VM_LIBRARY_DEFAULT, null);
+        assertFalse("the current default name has nothing to warn about, log was:\n" + out,
+                    out.contains(OLD_DEFAULT_LIBRARY));
+    }
+
+    public void testDeclaredMacroLibraryNeverWarns()
+    {
+        String out = warningsAtInitWithLibrary(true, RuntimeConstants.OLD_VM_LIBRARY_DEFAULT, RuntimeConstants.OLD_VM_LIBRARY_DEFAULT);
+        assertFalse("a declared library has nothing to warn about, log was:\n" + out,
+                    out.contains(OLD_DEFAULT_LIBRARY));
+    }
+
+    public void testOldDefaultMacroLibrarySilentWhenNoneIsThere()
+    {
+        String out = warningsAtInit(settingEngine(true, null, null));
+        assertFalse("no library, no warning, log was:\n" + out, out.contains(OLD_DEFAULT_LIBRARY));
+    }
+
+    public void testOldDefaultMacroLibrarySilentWhenDeprecationOff()
+    {
+        String out = warningsAtInitWithLibrary(false, RuntimeConstants.OLD_VM_LIBRARY_DEFAULT, null);
+        assertFalse("no warning expected with runtime.deprecation.warn = false, log was:\n" + out,
+                    out.contains(OLD_DEFAULT_LIBRARY));
+    }
+
 }


(velocity-engine) 08/09: SecureUberspector checks Class receivers before static-method lookup

Posted by cb...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/velocity-engine.git

commit a6f7fc885e69c2cbbf1a169c77dcd8b08e07808e
Author: Claude Brisson <cl...@renegat.net>
AuthorDate: Sun Sep 13 19:02:18 2026 +0200

    SecureUberspector checks Class receivers before static-method lookup
---
 src/changes/changes.xml                            |  6 +++
 .../util/introspection/SecureIntrospectorImpl.java |  3 +-
 .../util/introspection/SecureUberspector.java      | 26 ++++++++++++
 .../velocity/test/SecureIntrospectionTestCase.java | 48 ++++++++++++++++++++++
 4 files changed, 82 insertions(+), 1 deletion(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index ba561372..2fdf3408 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -39,6 +39,12 @@
 
   <body>
     <release version="2.5" date="2026-06-14">
+        <action type="fix" dev="cbrisson">
+            <code>SecureUberspector</code> now checks <code>Class</code> receivers against
+            <code>Class</code> before the superclass looks a method up among the static
+            methods of the class they name (VELOCITY-102): reached that way, only
+            <code>getName()</code> goes through, whatever the named class.
+        </action>
         <action type="fix" dev="cbrisson">
             Resource names are now normalized before being looked up by the loaders which
             resolve them against a root (file, classpath, jar and URL loaders): the
diff --git a/velocity-engine-core/src/main/java/org/apache/velocity/util/introspection/SecureIntrospectorImpl.java b/velocity-engine-core/src/main/java/org/apache/velocity/util/introspection/SecureIntrospectorImpl.java
index 2dc8320e..00d36c5a 100644
--- a/velocity-engine-core/src/main/java/org/apache/velocity/util/introspection/SecureIntrospectorImpl.java
+++ b/velocity-engine-core/src/main/java/org/apache/velocity/util/introspection/SecureIntrospectorImpl.java
@@ -136,7 +136,8 @@ public Method getMethod(Class<?> clazz, String methodName, Object[] params)
 
     /**
      * Determine which methods and classes to prevent from executing.  Always blocks
-     * methods wait() and notify().  Always allows methods on Number, Boolean, and String.
+     * methods wait() and notify().  Always allows the instance methods of Number, Boolean
+     * and String.
      * Prohibits method calls on classes related to reflection and system operations.
      * For the complete list, see the properties <code>introspector.restrict.classes</code>,
      * <code>introspector.restrict.packages</code> and <code>introspector.restrict.methods</code>.
diff --git a/velocity-engine-core/src/main/java/org/apache/velocity/util/introspection/SecureUberspector.java b/velocity-engine-core/src/main/java/org/apache/velocity/util/introspection/SecureUberspector.java
index e9fa3fec..487aed3d 100644
--- a/velocity-engine-core/src/main/java/org/apache/velocity/util/introspection/SecureUberspector.java
+++ b/velocity-engine-core/src/main/java/org/apache/velocity/util/introspection/SecureUberspector.java
@@ -60,6 +60,32 @@ public void init()
         introspector = new SecureIntrospectorImpl(badClasses, badPackages, badMethods, log);
     }
 
+    /**
+     * Get a method from the given object. When the object is a <code>Class</code>, only allow <code>Class.getName()</code>.
+     *
+     * @param obj object on which the method is called
+     * @param methodName name of the called method
+     * @param args method arguments
+     * @param i line, column, template info
+     * @return Velocity method, or null when the call is not permitted
+     * @since 2.5
+     */
+    @Override
+    public VelMethod getMethod(Object obj, String methodName, Object[] args, Info i)
+    {
+        if (obj instanceof Class)
+        {
+            SecureIntrospectorControl sic = (SecureIntrospectorControl)introspector;
+            if (!sic.checkObjectExecutePermission(Class.class, methodName))
+            {
+                log.warn("Cannot retrieve method {} from object of class {} due to security restrictions."
+                         , methodName, Class.class.getName());
+                return null;
+            }
+        }
+        return super.getMethod(obj, methodName, args, i);
+    }
+
     /**
      * Get an iterator from the given object.  Since the superclass method
      * this secure version checks for execute permission.
diff --git a/velocity-engine-core/src/test/java/org/apache/velocity/test/SecureIntrospectionTestCase.java b/velocity-engine-core/src/test/java/org/apache/velocity/test/SecureIntrospectionTestCase.java
index 0bb98a49..6650faab 100644
--- a/velocity-engine-core/src/test/java/org/apache/velocity/test/SecureIntrospectionTestCase.java
+++ b/velocity-engine-core/src/test/java/org/apache/velocity/test/SecureIntrospectionTestCase.java
@@ -252,6 +252,54 @@ public void testRestrictedMethodUnknownClass() throws Exception
                    doesStringEvaluate(ve, c, "$p.forbidden()"));
     }
 
+    /**
+     * A static method reached through a Class object is checked against Class, and not
+     * against the class it names: only getName() goes through.
+     */
+    public void testStaticMethodsThroughClassObject() throws Exception
+    {
+        System.setProperty("velocity.test.secure.int", "42");
+        System.setProperty("velocity.test.secure.bool", "true");
+
+        VelocityEngine ve = new VelocityEngine();
+        ve.setProperty(RuntimeConstants.UBERSPECT_CLASSNAME, SecureUberspector.class.getName());
+        ve.init();
+
+        Context c = new VelocityContext();
+        c.put("n", 1);
+        c.put("b", Boolean.TRUE);
+        c.put("s", "abcde");
+
+        /*
+         * reading a system property through the class of a whitelisted instance
+         */
+        assertFalse("Integer.getInteger must be blocked",
+                    doesStringEvaluate(ve, c, "$n.getClass().getInteger('velocity.test.secure.int')"));
+        assertFalse("Integer.getInteger must be blocked through the class property too",
+                    doesStringEvaluate(ve, c, "$n.class.getInteger('velocity.test.secure.int')"));
+        assertFalse("Boolean.getBoolean must be blocked",
+                    doesStringEvaluate(ve, c, "$b.getClass().getBoolean('velocity.test.secure.bool')"));
+        assertFalse("Class.forName must be blocked",
+                    doesStringEvaluate(ve, c, "$s.getClass().forName('java.lang.Runtime')"));
+        assertFalse("static parsing methods are blocked as well",
+                    doesStringEvaluate(ve, c, "$n.getClass().parseInt('7')"));
+
+        /*
+         * what the secure introspector does allow stays allowed
+         */
+        assertEquals("java.lang.Integer", render(ve, c, "$n.getClass().getName()"));
+        assertEquals("java.lang.Integer", render(ve, c, "$n.Class.Name"));
+        assertEquals("1", render(ve, c, "$n.intValue()"));
+        assertEquals("5", render(ve, c, "$s.length()"));
+    }
+
+    private String render(VelocityEngine ve, Context c, String inputString) throws Exception
+    {
+        Writer w = new StringWriter();
+        ve.evaluate(c, w, "foo", inputString);
+        return w.toString();
+    }
+
     /**
      * The default-shipped restriction on VelocityEngine.init must block that call from a template.
      */


(velocity-engine) 07/09: Resource loaders now enforce templates paths to stay in their configured root

Posted by cb...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/velocity-engine.git

commit 16a6993372aa2cc4f40309b06a9d1b9fc42e3492
Author: Claude Brisson <cl...@renegat.net>
AuthorDate: Tue Sep 15 11:31:55 2026 +0200

    Resource loaders now enforce templates paths to stay in their configured root
---
 src/changes/changes.xml                            |   9 +
 .../apache/velocity/runtime/directive/Include.java |   8 +-
 .../resource/loader/ClasspathResourceLoader.java   |   6 +
 .../resource/loader/DataSourceResourceLoader.java  |  13 ++
 .../resource/loader/FileResourceLoader.java        |  54 +++++-
 .../runtime/resource/loader/JarResourceLoader.java |   6 +
 .../runtime/resource/loader/ResourceLoader.java    |  77 ++++++++
 .../resource/loader/StringResourceLoader.java      |  13 ++
 .../runtime/resource/loader/URLResourceLoader.java |   6 +
 .../test/ResourceNameNormalizationTestCase.java    | 205 +++++++++++++++++++++
 .../src/test/resources/normalization/outside.txt   |   1 +
 .../src/test/resources/normalization/root/inc.vm   |   1 +
 .../resources/normalization/root/includedown.vm    |   1 +
 .../test/resources/normalization/root/includeup.vm |   1 +
 .../test/resources/normalization/root/parseup.vm   |   1 +
 .../test/resources/normalization/root/sub/inner.vm |   1 +
 16 files changed, 393 insertions(+), 10 deletions(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 59148f9e..ba561372 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -39,6 +39,15 @@
 
   <body>
     <release version="2.5" date="2026-06-14">
+        <action type="fix" dev="cbrisson">
+            Resource names are now normalized before being looked up by the loaders which
+            resolve them against a root (file, classpath, jar and URL loaders): the
+            <code>.</code> and <code>..</code> segments are collapsed, and a name climbing
+            above the root is refused, as if the resource did not exist. Loaders which use
+            the name as an opaque key (<code>DataSourceResourceLoader</code>,
+            <code>StringResourceLoader</code>) keep seeing it unchanged. See
+            <code>ResourceLoader.normalizeResourceName()</code>.
+        </action>
         <action type="fix" dev="cbrisson">
             <code>#evaluate</code> now honours the nesting depth limit set by
             <code>directive.parse.max_depth</code> (10 by default, zero or less meaning no
diff --git a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/directive/Include.java b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/directive/Include.java
index 1a333597..eb7ffefd 100644
--- a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/directive/Include.java
+++ b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/directive/Include.java
@@ -42,10 +42,10 @@
  *
  * <p>Notes:</p>
  * <ol>
- * <li>For security reasons, the included source material can only come
- *    from somewhere within the template root tree.  If you want to include
- *    content from elsewhere on your disk, add extra template roots, or use
- *    a link from somwehere under template root to that content.</li>
+ * <li>The included source material must lie within a configured resource root:
+ *    a name climbing above it is refused by the resource loaders. If you want to
+ *    include content from elsewhere on your disk, add extra template roots, or use
+ *    a link from somewhere under a template root to that content.</li>
  *
  *  <li>By default, there is no output to the render stream in the event of
  *    a problem.  You can override this behavior with two property values :
diff --git a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/resource/loader/ClasspathResourceLoader.java b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/resource/loader/ClasspathResourceLoader.java
index 9bfd0f14..b82598ae 100644
--- a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/resource/loader/ClasspathResourceLoader.java
+++ b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/resource/loader/ClasspathResourceLoader.java
@@ -111,6 +111,12 @@ public Reader getResourceReader(String name, String encoding )
             throw new ResourceNotFoundException ("No template name provided");
         }
 
+        name = normalizeResourceName(name);
+        if (name == null)
+        {
+            throw new ResourceNotFoundException("ClasspathResourceLoader Error: resource name is invalid");
+        }
+
         /*
          * look for resource in thread classloader first (e.g. WEB-INF\lib in
          * a servlet container) then fall back to the system classloader.
diff --git a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/resource/loader/DataSourceResourceLoader.java b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/resource/loader/DataSourceResourceLoader.java
index a6561720..67a14485 100644
--- a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/resource/loader/DataSourceResourceLoader.java
+++ b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/resource/loader/DataSourceResourceLoader.java
@@ -313,6 +313,19 @@ public void setDataSource(final DataSource dataSource)
         this.dataSource = dataSource;
     }
 
+    /**
+     * Resource names are opaque keys here: they are used as given.
+     *
+     * @param name resource name
+     * @return the name, unchanged
+     * @since 2.5
+     */
+    @Override
+    public String normalizeResourceName(String name)
+    {
+        return name;
+    }
+
     /**
      * @see ResourceLoader#isSourceModified(org.apache.velocity.runtime.resource.Resource)
      */
diff --git a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/resource/loader/FileResourceLoader.java b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/resource/loader/FileResourceLoader.java
index 8993b7c7..f5157b04 100644
--- a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/resource/loader/FileResourceLoader.java
+++ b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/resource/loader/FileResourceLoader.java
@@ -33,6 +33,8 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.Reader;
+import java.nio.file.Path;
+import java.nio.file.Paths;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashMap;
@@ -170,7 +172,7 @@ public boolean resourceExists(String name)
             try
             {
                 File file = getFile(path, name);
-                if (file.canRead())
+                if (file != null && file.canRead())
                 {
                     return true;
                 }
@@ -198,7 +200,7 @@ private InputStream findTemplate(final String path, final String template)
         {
             File file = getFile(path, template);
 
-            if (file.canRead())
+            if (file != null && file.canRead())
             {
                 FileInputStream fis = null;
                 try
@@ -269,13 +271,13 @@ public boolean isSourceModified(Resource resource)
         {
             String testPath = (String) paths.get(i);
             File testFile = getFile(testPath, fileName);
-            if (testFile.canRead())
+            if (testFile != null && testFile.canRead())
             {
                 currentFile = testFile;
             }
         }
         File file = getFile(path, fileName);
-        if (currentFile == null || !file.exists())
+        if (currentFile == null || file == null || !file.exists())
         {
             /*
              * noop: if the file is missing now (either the cached
@@ -312,7 +314,7 @@ public long getLastModified(Resource resource)
         String path = templatePaths.get(resource.getName());
         File file = getFile(path, resource.getName());
 
-        if (file.canRead())
+        if (file != null && file.canRead())
         {
             return file.lastModified();
         }
@@ -324,7 +326,10 @@ public long getLastModified(Resource resource)
 
 
     /**
-     * Create a File based on either a relative path if given, or absolute path otherwise
+     * Create a File based on either a relative path if given, or absolute path otherwise.
+     *
+     * @return the file to read, or null when the template name does not resolve
+     *         inside the given path
      */
     private File getFile(String path, String template)
     {
@@ -333,10 +338,17 @@ private File getFile(String path, String template)
 
         if("".equals(path))
         {
+            /* an empty path is an explicit configuration choice: absolute names are allowed */
             file = new File( template );
         }
         else
         {
+            template = normalizeResourceName(template);
+            if (template == null)
+            {
+                return null;
+            }
+
             /*
              *  if a / leads off, then just nip that :)
              */
@@ -346,8 +358,38 @@ private File getFile(String path, String template)
             }
 
             file = new File ( path, template );
+
+            /* refuse to escape root path */
+            if (path != null && !isInside(path, file))
+            {
+                return null;
+            }
         }
 
         return file;
     }
+
+    /**
+     * Tell whether the given file lies inside the given path. Paths are normalized but
+     * symbolic links are not resolved, so that a linked template stays reachable.
+     */
+    private boolean isInside(String path, File file)
+    {
+        try
+        {
+            Path root = Paths.get(path).toAbsolutePath().normalize();
+            Path target = file.toPath().toAbsolutePath().normalize();
+            if (target.startsWith(root))
+            {
+                return true;
+            }
+            log.debug("FileResourceLoader: template '{}' is not inside path '{}'", file, path);
+        }
+        catch (RuntimeException re)
+        {
+            /* invalid path: not something we can read */
+            log.debug("FileResourceLoader: cannot resolve template '{}' inside path '{}'", file, path);
+        }
+        return false;
+    }
 }
diff --git a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/resource/loader/JarResourceLoader.java b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/resource/loader/JarResourceLoader.java
index 4f56bf50..75af3af6 100644
--- a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/resource/loader/JarResourceLoader.java
+++ b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/resource/loader/JarResourceLoader.java
@@ -185,6 +185,12 @@ public Reader getResourceReader(String source, String encoding )
             throw new ResourceNotFoundException("Need to have a resource!");
         }
 
+        source = normalizeResourceName(source);
+        if (source == null)
+        {
+            throw new ResourceNotFoundException("JarResourceLoader Error: resource name is invalid");
+        }
+
         /*
          *  if a / leads off, then just nip that :)
          */
diff --git a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/resource/loader/ResourceLoader.java b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/resource/loader/ResourceLoader.java
index 9a2d5643..40dff648 100644
--- a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/resource/loader/ResourceLoader.java
+++ b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/resource/loader/ResourceLoader.java
@@ -35,6 +35,8 @@
 import java.io.InputStreamReader;
 import java.io.Reader;
 import java.io.UnsupportedEncodingException;
+import java.util.ArrayList;
+import java.util.List;
 
 /**
  * This is abstract class the all text resource loaders should
@@ -228,6 +230,81 @@ public long getModificationCheckInterval()
         return modificationCheckInterval;
     }
 
+    /**
+     * <p>Normalize a resource name before it is looked up, and tell whether it is acceptable
+     * at all. The default implementation collapses the <code>.</code> and <code>..</code>
+     * segments of the name, taking <code>/</code> as the separator, and returns
+     * <code>null</code> for a name whose <code>..</code> segments climb above the resource
+     * root: <code>a/../b.vm</code> is <code>b.vm</code>, while <code>../b.vm</code> and
+     * <code>a/../../b.vm</code> are refused. A leading <code>/</code> is preserved, each
+     * loader having its own way of handling it.</p>
+     *
+     * <p>This is meant for the loaders which resolve a name against one or several roots
+     * (file, classpath, jar and URL loaders do call it, and refuse a name for which it
+     * returns <code>null</code>). Loaders which use the name as an opaque key, like
+     * <code>DataSourceResourceLoader</code> and <code>StringResourceLoader</code>, do not
+     * call it: their keys may contain anything, including <code>..</code> segments.</p>
+     *
+     * @param name resource name, as asked by the application or by a directive
+     * @return the name to look up, or <code>null</code> if the name is not acceptable
+     * @since 2.5
+     */
+    public String normalizeResourceName(String name)
+    {
+        if (name == null || name.indexOf('.') == -1)
+        {
+            /* without a dot, the name cannot contain any . or .. segment */
+            return name;
+        }
+
+        boolean absolute = name.startsWith("/");
+        String[] segments = (absolute ? name.substring(1) : name).split("/", -1);
+        List<String> kept = new ArrayList<>(segments.length);
+        boolean changed = false;
+
+        for (String segment : segments)
+        {
+            if (".".equals(segment))
+            {
+                changed = true;
+            }
+            else if ("..".equals(segment))
+            {
+                if (kept.isEmpty())
+                {
+                    /* climbs above the root */
+                    return null;
+                }
+                kept.remove(kept.size() - 1);
+                changed = true;
+            }
+            else
+            {
+                kept.add(segment);
+            }
+        }
+
+        if (!changed)
+        {
+            return name;
+        }
+
+        StringBuilder normalized = new StringBuilder(name.length());
+        if (absolute)
+        {
+            normalized.append('/');
+        }
+        for (int i = 0; i < kept.size(); i++)
+        {
+            if (i > 0)
+            {
+                normalized.append('/');
+            }
+            normalized.append(kept.get(i));
+        }
+        return normalized.toString();
+    }
+
     /**
      * Check whether any given resource exists. This is not really
      * a very efficient test and it can and should be overridden in the
diff --git a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/resource/loader/StringResourceLoader.java b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/resource/loader/StringResourceLoader.java
index fd5d8c4a..23b441a2 100644
--- a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/resource/loader/StringResourceLoader.java
+++ b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/resource/loader/StringResourceLoader.java
@@ -346,6 +346,19 @@ public boolean resourceExists(final String name)
         return (this.repository.getStringResource(name) != null);
     }
 
+    /**
+     * Resource names are opaque keys here: they are used as given.
+     *
+     * @param name resource name
+     * @return the name, unchanged
+     * @since 2.5
+     */
+    @Override
+    public String normalizeResourceName(String name)
+    {
+        return name;
+    }
+
     /**
      * Get a reader so that the Runtime can build a
      * template with it.
diff --git a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/resource/loader/URLResourceLoader.java b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/resource/loader/URLResourceLoader.java
index 81fe33b9..ff4c9ead 100644
--- a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/resource/loader/URLResourceLoader.java
+++ b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/resource/loader/URLResourceLoader.java
@@ -92,6 +92,12 @@ public synchronized Reader getResourceReader(String name, String encoding)
             throw new ResourceNotFoundException("URLResourceLoader: No template name provided");
         }
 
+        name = normalizeResourceName(name);
+        if (name == null)
+        {
+            throw new ResourceNotFoundException("URLResourceLoader: resource name is invalid");
+        }
+
         Reader reader = null;
         Exception exception = null;
         for (String root : roots)
diff --git a/velocity-engine-core/src/test/java/org/apache/velocity/test/ResourceNameNormalizationTestCase.java b/velocity-engine-core/src/test/java/org/apache/velocity/test/ResourceNameNormalizationTestCase.java
new file mode 100644
index 00000000..bbdfb71d
--- /dev/null
+++ b/velocity-engine-core/src/test/java/org/apache/velocity/test/ResourceNameNormalizationTestCase.java
@@ -0,0 +1,205 @@
+package org.apache.velocity.test;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import org.apache.velocity.Template;
+import org.apache.velocity.VelocityContext;
+import org.apache.velocity.app.VelocityEngine;
+import org.apache.velocity.exception.ResourceNotFoundException;
+import org.apache.velocity.runtime.RuntimeConstants;
+import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
+import org.apache.velocity.runtime.resource.loader.ResourceLoader;
+import org.apache.velocity.runtime.resource.loader.StringResourceLoader;
+import org.apache.velocity.runtime.resource.util.StringResourceRepository;
+
+import java.io.StringWriter;
+
+/**
+ * Tests the normalization of resource names, and the refusal of a name which
+ * climbs above the resource root.
+ */
+public class ResourceNameNormalizationTestCase extends BaseTestCase
+{
+    private static final String ROOT = TEST_COMPARE_DIR + "/normalization/root";
+
+    public ResourceNameNormalizationTestCase(String name)
+    {
+        super(name);
+    }
+
+    /**
+     * An engine whose file loader is rooted in the normalization directory.
+     */
+    private VelocityEngine fileEngine()
+    {
+        VelocityEngine ve = new VelocityEngine();
+        ve.setProperty(RuntimeConstants.RESOURCE_LOADERS, "file");
+        ve.setProperty("resource.loader.file.path", ROOT);
+        ve.setProperty(RuntimeConstants.RUNTIME_LOG_INSTANCE, log);
+        ve.init();
+        return ve;
+    }
+
+    private String merge(VelocityEngine ve, String templateName)
+    {
+        Template template = ve.getTemplate(templateName);
+        StringWriter writer = new StringWriter();
+        template.merge(new VelocityContext(), writer);
+        return writer.toString();
+    }
+
+    /**
+     * The default normalization collapses . and .. segments, and refuses a name
+     * climbing above the root.
+     */
+    public void testDefaultNormalization()
+    {
+        ResourceLoader loader = new ClasspathResourceLoader();
+
+        assertEquals("a.vm", loader.normalizeResourceName("a.vm"));
+        assertEquals("sub/a.vm", loader.normalizeResourceName("sub/a.vm"));
+        assertEquals("a.vm", loader.normalizeResourceName("./a.vm"));
+        assertEquals("a.vm", loader.normalizeResourceName("sub/../a.vm"));
+        assertEquals("sub/a.vm", loader.normalizeResourceName("sub/deeper/../a.vm"));
+        assertEquals("/sub/a.vm", loader.normalizeResourceName("/sub/deeper/../a.vm"));
+
+        assertNull(loader.normalizeResourceName("../a.vm"));
+        assertNull(loader.normalizeResourceName("sub/../../a.vm"));
+        assertNull(loader.normalizeResourceName("/../a.vm"));
+    }
+
+    /**
+     * A template name climbing above the file loader root is not found.
+     */
+    public void testFileLoaderRefusesClimbingName()
+    {
+        VelocityEngine ve = fileEngine();
+
+        // the file is really there, one level above the root
+        assertTrue(new java.io.File(TEST_COMPARE_DIR + "/normalization/outside.txt").canRead());
+
+        try
+        {
+            ve.getTemplate("../outside.txt");
+            fail("Expected ResourceNotFoundException");
+        }
+        catch (ResourceNotFoundException rnfe)
+        {
+            // the message names the resource as asked
+            assertTrue(rnfe.getMessage(), rnfe.getMessage().contains("../outside.txt"));
+        }
+
+        assertFalse(ve.resourceExists("../outside.txt"));
+    }
+
+    /**
+     * Same through #include and #parse.
+     */
+    public void testDirectivesRefuseClimbingName()
+    {
+        VelocityEngine ve = fileEngine();
+
+        try
+        {
+            merge(ve, "includeup.vm");
+            fail("Expected ResourceNotFoundException");
+        }
+        catch (ResourceNotFoundException rnfe)
+        {
+            // expected
+        }
+
+        try
+        {
+            merge(ve, "parseup.vm");
+            fail("Expected ResourceNotFoundException");
+        }
+        catch (ResourceNotFoundException rnfe)
+        {
+            // expected
+        }
+    }
+
+    /**
+     * A name whose .. segments stay inside the root is found.
+     */
+    public void testFileLoaderAcceptsInnerName()
+    {
+        VelocityEngine ve = fileEngine();
+
+        assertEquals("inner", merge(ve, "sub/inner.vm"));
+        assertEquals("included", merge(ve, "sub/../inc.vm"));
+        assertEquals("included", merge(ve, "./inc.vm"));
+        assertEquals("inner", merge(ve, "sub/../sub/inner.vm"));
+
+        assertTrue(ve.resourceExists("sub/../inc.vm"));
+
+        // and through #include
+        assertEquals("included", merge(ve, "includedown.vm"));
+    }
+
+    /**
+     * The classpath loader refuses a climbing name too.
+     */
+    public void testClasspathLoaderRefusesClimbingName()
+    {
+        VelocityEngine ve = new VelocityEngine();
+        ve.setProperty(RuntimeConstants.RESOURCE_LOADERS, "class");
+        ve.setProperty("resource.loader.class.class", ClasspathResourceLoader.class.getName());
+        ve.setProperty(RuntimeConstants.RUNTIME_LOG_INSTANCE, log);
+        ve.init();
+
+        // the resource is there under its plain name
+        assertEquals("included", merge(ve, "normalization/root/inc.vm"));
+
+        try
+        {
+            ve.getTemplate("normalization/root/../../normalization/../../inc.vm");
+            fail("Expected ResourceNotFoundException");
+        }
+        catch (ResourceNotFoundException rnfe)
+        {
+            // expected
+        }
+    }
+
+    /**
+     * The string loader uses the name as an opaque key: it is left untouched.
+     */
+    public void testStringLoaderKeepsKeyUntouched()
+    {
+        VelocityEngine ve = new VelocityEngine();
+        ve.setProperty(RuntimeConstants.RESOURCE_LOADERS, "string");
+        ve.setProperty("resource.loader.string.class", StringResourceLoader.class.getName());
+        ve.setProperty("resource.loader.string.repository.name", "normalization.repo");
+        ve.setProperty("resource.loader.string.repository.static", "false");
+        ve.setProperty(RuntimeConstants.RUNTIME_LOG_INSTANCE, log);
+        ve.init();
+
+        StringResourceRepository repo =
+            (StringResourceRepository)ve.getApplicationAttribute("normalization.repo");
+        repo.putStringResource("../up.vm", "from the key with dots");
+        repo.putStringResource("a/../b.vm", "another key with dots");
+
+        assertEquals("from the key with dots", merge(ve, "../up.vm"));
+        assertEquals("another key with dots", merge(ve, "a/../b.vm"));
+        assertEquals("../up.vm", new StringResourceLoader().normalizeResourceName("../up.vm"));
+    }
+}
diff --git a/velocity-engine-core/src/test/resources/normalization/outside.txt b/velocity-engine-core/src/test/resources/normalization/outside.txt
new file mode 100644
index 00000000..0760d231
--- /dev/null
+++ b/velocity-engine-core/src/test/resources/normalization/outside.txt
@@ -0,0 +1 @@
+OUTSIDE
diff --git a/velocity-engine-core/src/test/resources/normalization/root/inc.vm b/velocity-engine-core/src/test/resources/normalization/root/inc.vm
new file mode 100644
index 00000000..28ea5a74
--- /dev/null
+++ b/velocity-engine-core/src/test/resources/normalization/root/inc.vm
@@ -0,0 +1 @@
+included
\ No newline at end of file
diff --git a/velocity-engine-core/src/test/resources/normalization/root/includedown.vm b/velocity-engine-core/src/test/resources/normalization/root/includedown.vm
new file mode 100644
index 00000000..5a6577c6
--- /dev/null
+++ b/velocity-engine-core/src/test/resources/normalization/root/includedown.vm
@@ -0,0 +1 @@
+#include("sub/../inc.vm")
\ No newline at end of file
diff --git a/velocity-engine-core/src/test/resources/normalization/root/includeup.vm b/velocity-engine-core/src/test/resources/normalization/root/includeup.vm
new file mode 100644
index 00000000..a42c9eaa
--- /dev/null
+++ b/velocity-engine-core/src/test/resources/normalization/root/includeup.vm
@@ -0,0 +1 @@
+#include("../outside.txt")
\ No newline at end of file
diff --git a/velocity-engine-core/src/test/resources/normalization/root/parseup.vm b/velocity-engine-core/src/test/resources/normalization/root/parseup.vm
new file mode 100644
index 00000000..fba548bf
--- /dev/null
+++ b/velocity-engine-core/src/test/resources/normalization/root/parseup.vm
@@ -0,0 +1 @@
+#parse("../outside.txt")
\ No newline at end of file
diff --git a/velocity-engine-core/src/test/resources/normalization/root/sub/inner.vm b/velocity-engine-core/src/test/resources/normalization/root/sub/inner.vm
new file mode 100644
index 00000000..6b83a3b8
--- /dev/null
+++ b/velocity-engine-core/src/test/resources/normalization/root/sub/inner.vm
@@ -0,0 +1 @@
+inner
\ No newline at end of file


(velocity-engine) 01/09: Deprecate velocimacro.enable_bc_mode without replacement

Posted by cb...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/velocity-engine.git

commit 9e53f0f149bd6edfd6ab08f2f52195a57f7fea92
Author: Claude Brisson <cl...@renegat.net>
AuthorDate: Sun Sep 13 19:06:57 2026 +0200

    Deprecate velocimacro.enable_bc_mode without replacement
---
 .../apache/velocity/runtime/RuntimeConstants.java  |  4 ++
 .../apache/velocity/runtime/RuntimeInstance.java   |  6 ++
 .../velocity/test/DeprecationWarningTestCase.java  | 74 ++++++++++++++++++++++
 3 files changed, 84 insertions(+)

diff --git a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeConstants.java b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeConstants.java
index fbb6723b..feb5d97e 100644
--- a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeConstants.java
+++ b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeConstants.java
@@ -355,7 +355,11 @@ public interface RuntimeConstants extends DeprecatedRuntimeConstants
      *     </li>
      * </ul>
      * @since 2.2
+     * @deprecated since 2.5, without replacement: the next major version does not provide this
+     * compatibility mode; a null argument renders the parameter's own literal and a missing
+     * argument is null, as since 2.0.
      */
+    @Deprecated
     String VM_ENABLE_BC_MODE = "velocimacro.enable_bc_mode";
 
     /**
diff --git a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeInstance.java b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeInstance.java
index 712dfe22..6f025f81 100644
--- a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeInstance.java
+++ b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeInstance.java
@@ -406,6 +406,7 @@ private void initializeSelfProperties()
      * Warns about deprecated configuration settings, when runtime.deprecation.warn is on.
      * Kept separate from {@link #initializeSelfProperties()} so it runs after the log is set up.
      */
+    @SuppressWarnings("deprecation")
     private void warnDeprecatedSettings()
     {
         if (!getBoolean(RUNTIME_DEPRECATION_WARN, true))
@@ -422,6 +423,11 @@ private void warnDeprecatedSettings()
         {
             log.warn("{} is false: lenient math is deprecated, set it to true to fix this warning - math operations on null or non-numeric operands and divisions by zero will not silently be skipped.", STRICT_MATH);
         }
+
+        if (getBoolean(VM_ENABLE_BC_MODE, false))
+        {
+            log.warn("the '{}' setting is deprecated without replacement: the next major version does not provide this compatibility mode", VM_ENABLE_BC_MODE);
+        }
     }
 
     private char getConfiguredCharacter(String configKey, char defaultChar)
diff --git a/velocity-engine-core/src/test/java/org/apache/velocity/test/DeprecationWarningTestCase.java b/velocity-engine-core/src/test/java/org/apache/velocity/test/DeprecationWarningTestCase.java
index d2ce7672..39b278fd 100644
--- a/velocity-engine-core/src/test/java/org/apache/velocity/test/DeprecationWarningTestCase.java
+++ b/velocity-engine-core/src/test/java/org/apache/velocity/test/DeprecationWarningTestCase.java
@@ -23,6 +23,7 @@
 import org.apache.velocity.exception.MathException;
 import org.apache.velocity.runtime.RuntimeConstants;
 import org.apache.velocity.runtime.resource.loader.StringResourceLoader;
+import org.apache.velocity.test.misc.TestVelocityEngine;
 
 import java.util.Properties;
 
@@ -34,6 +35,10 @@
  *   <li>a lone backslash right before the closing quote of a double-quoted string</li>
  *   <li>{@code runtime.strict_math = false}
  * </ul>
+ * and the settings the next major version does not provide any more:
+ * <ul>
+ *   <li>{@code velocimacro.enable_bc_mode}</li>
+ * </ul>
  */
 public class DeprecationWarningTestCase extends BaseTestCase
 {
@@ -412,4 +417,73 @@ public void testExplicitFalseSilencesTheWarning() throws Exception
         assertFalse("no warning expected with runtime.deprecation.warn = false, log was:\n" + out,
                     out.contains("deprecated"));
     }
+
+    /* ---- settings the next major version does not provide: warned once at engine init ---- */
+
+    /**
+     * An engine with one setting of interest, and nothing else to warn about: strict math is on,
+     * so the lenient-math warning stays out of these logs.
+     *
+     * @param warn value of runtime.deprecation.warn
+     * @param key the setting to apply, or null to apply none
+     * @param value its value
+     * @return the engine, not initialized yet
+     */
+    private VelocityEngine settingEngine(boolean warn, String key, String value)
+    {
+        VelocityEngine ve = new TestVelocityEngine();
+        ve.setProperty(RuntimeConstants.RUNTIME_LOG_INSTANCE, log);
+        ve.setProperty(RuntimeConstants.RESOURCE_LOADERS, "string");
+        ve.addProperty("resource.loader.string.class", StringResourceLoader.class.getName());
+        ve.setProperty(RuntimeConstants.RUNTIME_DEPRECATION_WARN, String.valueOf(warn));
+        if (key != null && value != null)
+        {
+            ve.setProperty(key, value);
+        }
+        return ve;
+    }
+
+    private void assertWarnsAtInit(String needle, boolean warn, String key, String value)
+    {
+        String out = warningsAtInit(settingEngine(warn, key, value));
+        assertTrue("expected a deprecation warning naming '" + needle + "', log was:\n" + out,
+                   out.contains(needle) && out.contains("deprecated"));
+    }
+
+    private void assertSilentAtInit(String needle, boolean warn, String key, String value)
+    {
+        String out = warningsAtInit(settingEngine(warn, key, value));
+        assertFalse("unexpected deprecation warning naming '" + needle + "', log was:\n" + out,
+                    out.contains(needle));
+    }
+
+    /* ---- velocimacro.enable_bc_mode: deprecated without replacement ---- */
+
+    public void testBcModeWarnsWhenEnabled()
+    {
+        assertWarnsAtInit(RuntimeConstants.VM_ENABLE_BC_MODE, true, RuntimeConstants.VM_ENABLE_BC_MODE, "true");
+    }
+
+    public void testBcModeWarningSaysWithoutReplacement()
+    {
+        String out = warningsAtInit(settingEngine(true, RuntimeConstants.VM_ENABLE_BC_MODE, "true"));
+        assertTrue("the warning must say there is no replacement, log was:\n" + out,
+                   out.contains("without replacement"));
+    }
+
+    public void testBcModeSilentWhenDisabled()
+    {
+        assertSilentAtInit(RuntimeConstants.VM_ENABLE_BC_MODE, true, RuntimeConstants.VM_ENABLE_BC_MODE, "false");
+    }
+
+    public void testBcModeSilentWhenDefaulted()
+    {
+        assertSilentAtInit(RuntimeConstants.VM_ENABLE_BC_MODE, true, null, null);
+    }
+
+    public void testBcModeSilentWhenDeprecationOff()
+    {
+        assertSilentAtInit(RuntimeConstants.VM_ENABLE_BC_MODE, false, RuntimeConstants.VM_ENABLE_BC_MODE, "true");
+    }
+
 }


(velocity-engine) 05/09: Update changelog

Posted by cb...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/velocity-engine.git

commit 514cccbff4738cc451eefff9b26be3492513a3e0
Author: Claude Brisson <cl...@renegat.net>
AuthorDate: Tue Sep 15 09:28:52 2026 +0200

    Update changelog
---
 src/changes/changes.xml | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 575ee532..e47a4db5 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -52,6 +52,12 @@
             version); warnings gated by
             <code>runtime.deprecation.warn</code>, on by default.
         </action>
+        <action type="update" dev="cbrisson">
+            Deprecate macros old BC mode <code>velocimacro.enable_bc_mode</code>, old
+            default macros library name <code>VM_global_library.vm</code>,
+            <code>runtime.immutable_ranges = false</code>, and
+            <code>RuntimeServices.createNewParser()</code>.
+        </action>
         <action type="update" dev="cbrisson" issue="VELOCITY-994">
             <code>spring-velocity-support</code> now targets the current, Jakarta-based
             Spring framework (Spring 6.x and 7.x) on Java 17. The previous Spring 5.x /


(velocity-engine) 09/09: Deprecate parser.class property, as well as DOLLAR char customization

Posted by cb...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/velocity-engine.git

commit ae5215e85af970438499321022d9e73202135b56
Author: Claude Brisson <cl...@renegat.net>
AuthorDate: Tue Sep 15 12:29:05 2026 +0200

    Deprecate parser.class property, as well as DOLLAR char customization
---
 src/changes/changes.xml                            |  7 ++-
 .../apache/velocity/runtime/RuntimeConstants.java  | 13 ++++-
 .../apache/velocity/runtime/RuntimeInstance.java   | 30 +++++++++++
 .../velocity/test/DeprecationWarningTestCase.java  | 59 ++++++++++++++++++++++
 4 files changed, 106 insertions(+), 3 deletions(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 2fdf3408..e56c1b58 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -75,8 +75,11 @@
         <action type="update" dev="cbrisson">
             Deprecate macros old BC mode <code>velocimacro.enable_bc_mode</code>, old
             default macros library name <code>VM_global_library.vm</code>,
-            <code>runtime.immutable_ranges = false</code>, and
-            <code>RuntimeServices.createNewParser()</code>.
+            <code>runtime.immutable_ranges = false</code>,
+            <code>RuntimeServices.createNewParser()</code>, the <code>parser.class</code>
+            setting and the <code>parser.char.dollar</code> build property (the next major
+            version replaces the runtime parser properties by a pluggable lexer, and
+            <code>$</code> is not configurable there).
         </action>
         <action type="update" dev="cbrisson" issue="VELOCITY-994">
             <code>spring-velocity-support</code> now targets the current, Jakarta-based
diff --git a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeConstants.java b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeConstants.java
index de25cf41..ba1d839e 100644
--- a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeConstants.java
+++ b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeConstants.java
@@ -438,15 +438,26 @@ public interface RuntimeConstants extends DeprecatedRuntimeConstants
      */
 
     /**
-     * Property specifying the parser class to use
+     * Property specifying the parser class to use.
+     * <p>The four sigils the named parser lexes are not configured here: they are build-time inputs
+     * of its generation (the <code>parser.char.dollar</code>, <code>parser.char.hash</code>,
+     * <code>parser.char.at</code> and <code>parser.char.asterisk</code> properties of the build which
+     * generates it, as <code>velocity-custom-parser-example</code> shows), and the engine reads them
+     * back from the parser itself.</p>
      * @since 2.2
+     * @deprecated since 2.5: the next major version replaces the runtime parser properties by a
+     * pluggable lexer; this key has no effect there.
      */
+    @Deprecated
     String PARSER_CLASS = "parser.class";
 
     /**
      * Default parser class
      * @since 2.2
+     * @deprecated since 2.5, with {@link #PARSER_CLASS}: the next major version replaces the runtime
+     * parser properties by a pluggable lexer, and names another default.
      */
+    @Deprecated
     String DEFAULT_PARSER_CLASS = "org.apache.velocity.runtime.parser.StandardParser";
 
     /**
diff --git a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeInstance.java b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeInstance.java
index c82459f1..dbfef8b5 100644
--- a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeInstance.java
+++ b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeInstance.java
@@ -435,6 +435,35 @@ private void warnDeprecatedSettings()
         {
             log.warn("{} is false: mutable integer ranges are deprecated, ranges will always be immutable in the next major version", IMMUTABLE_RANGES);
         }
+
+        if (isExplicitlyConfigured(PARSER_CLASS))
+        {
+            log.warn("the '{}' setting is deprecated: the next major version replaces the runtime parser properties by a pluggable lexer, and this key has no effect there", PARSER_CLASS);
+        }
+
+        /*
+         * parser.char.dollar is a build-time input of the parser generation, which this engine never
+         * reads from the configuration: setting it expects a runtime effect it never had, and the next
+         * major version keeps the dollar for itself.
+         */
+        if (isExplicitlyConfigured(PARSER_CHAR_DOLLAR))
+        {
+            log.warn("the '{}' setting is deprecated: the '$' character will not be configurable in the next major version", PARSER_CHAR_DOLLAR);
+        }
+    }
+
+    /** the build-time property naming the character which stands for <code>$</code> in a generated parser */
+    private static final String PARSER_CHAR_DOLLAR = "parser.char.dollar";
+
+    /**
+     * Whether the application configured this property itself, as opposed to a shipped default value.
+     *
+     * @param key property key
+     * @return true if the property was set through any of the setProperty/addProperty/setProperties/setConfiguration methods
+     */
+    private boolean isExplicitlyConfigured(String key)
+    {
+        return overridingProperties != null && overridingProperties.containsKey(key);
     }
 
     private char getConfiguredCharacter(String configKey, char defaultChar)
@@ -1217,6 +1246,7 @@ public void loadDirective(String directiveClass)
     /**
      * Initializes the Velocity parser pool.
      */
+    @SuppressWarnings("deprecation")
     private void initializeParserPool()
     {
         /*
diff --git a/velocity-engine-core/src/test/java/org/apache/velocity/test/DeprecationWarningTestCase.java b/velocity-engine-core/src/test/java/org/apache/velocity/test/DeprecationWarningTestCase.java
index 1264f290..bdf60f7d 100644
--- a/velocity-engine-core/src/test/java/org/apache/velocity/test/DeprecationWarningTestCase.java
+++ b/velocity-engine-core/src/test/java/org/apache/velocity/test/DeprecationWarningTestCase.java
@@ -41,6 +41,7 @@
  *   <li>{@code velocimacro.enable_bc_mode}</li>
  *   <li>an implicitly loaded macro library</li>
  *   <li>{@code runtime.immutable_ranges = false}</li>
+ *   <li>{@code parser.class} and the {@code parser.char.dollar} build property</li>
  * </ul>
  */
 public class DeprecationWarningTestCase extends BaseTestCase
@@ -574,4 +575,62 @@ public void testMutableRangesSilentWhenDeprecationOff()
         assertSilentAtInit(RuntimeConstants.IMMUTABLE_RANGES, false, RuntimeConstants.IMMUTABLE_RANGES, "false");
     }
 
+
+
+    /* ---- the parser settings: deprecated, a pluggable lexer replaces them ---- */
+
+    /** the distinctive words of each of the two wordings */
+    private static final String PLUGGABLE_LEXER = "pluggable lexer";
+    private static final String DOLLAR_FIXED = "will not be configurable";
+
+    /** the shipped parser: the setting has to name a usable class for the engine to initialize */
+    @SuppressWarnings("deprecation")
+    private static final String STANDARD_PARSER = RuntimeConstants.DEFAULT_PARSER_CLASS;
+
+    @SuppressWarnings("deprecation")
+    public void testParserClassWarnsWhenSet()
+    {
+        String out = warningsAtInit(settingEngine(true, RuntimeConstants.PARSER_CLASS, STANDARD_PARSER));
+        assertTrue("setting the parser class must warn, log was:\n" + out,
+                   out.contains("deprecated") && out.contains("'parser.class'"));
+        assertTrue("the warning must say what replaces it, log was:\n" + out,
+                   out.contains(PLUGGABLE_LEXER));
+    }
+
+    /** the dollar is not configurable at all in the next major version */
+    public void testDollarSigilWarnsWhenSet()
+    {
+        String out = warningsAtInit(settingEngine(true, "parser.char.dollar", "$"));
+        assertTrue("setting 'parser.char.dollar' must warn, log was:\n" + out,
+                   out.contains("deprecated") && out.contains("'parser.char.dollar'"));
+        assertTrue("the warning must say the dollar stays fixed, log was:\n" + out,
+                   out.contains(DOLLAR_FIXED));
+    }
+
+    /** the other build properties of the parser generation are not runtime settings: no warning */
+    public void testOtherSigilKeysNeverWarn()
+    {
+        for (String key : new String[] { "parser.char.hash", "parser.char.at", "parser.char.asterisk" })
+        {
+            String out = warningsAtInit(settingEngine(true, key, "%"));
+            assertFalse("no warning expected for '" + key + "', log was:\n" + out,
+                        out.contains("'" + key + "'"));
+        }
+    }
+
+    /** nothing is shipped for either of them: an engine that asked for none has nothing to warn about */
+    public void testParserSettingsSilentWhenDefaulted()
+    {
+        String out = warningsAtInit(settingEngine(true, null, null));
+        assertFalse("no parser warning expected, log was:\n" + out,
+                    out.contains(PLUGGABLE_LEXER) || out.contains(DOLLAR_FIXED));
+    }
+
+    @SuppressWarnings("deprecation")
+    public void testParserSettingsSilentWhenDeprecationOff()
+    {
+        assertSilentAtInit(PLUGGABLE_LEXER, false, RuntimeConstants.PARSER_CLASS, STANDARD_PARSER);
+        assertSilentAtInit(DOLLAR_FIXED, false, "parser.char.dollar", "$");
+    }
+
 }


(velocity-engine) 03/09: Deprecate mutable integer ranges (runtime.immutable_ranges = false)

Posted by cb...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

asf-gitbox-commits pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/velocity-engine.git

commit 614ef32ddbd2423a29d27d7177a0f13b9379dd0c
Author: Claude Brisson <cl...@renegat.net>
AuthorDate: Sun Sep 13 19:02:18 2026 +0200

    Deprecate mutable integer ranges (runtime.immutable_ranges = false)
---
 .../apache/velocity/runtime/RuntimeConstants.java    |  6 +++++-
 .../org/apache/velocity/runtime/RuntimeInstance.java |  5 +++++
 .../velocity/test/DeprecationWarningTestCase.java    | 20 ++++++++++++++++++++
 3 files changed, 30 insertions(+), 1 deletion(-)

diff --git a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeConstants.java b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeConstants.java
index feb5d97e..8cedd936 100644
--- a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeConstants.java
+++ b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeConstants.java
@@ -474,7 +474,11 @@ public interface RuntimeConstants extends DeprecatedRuntimeConstants
     /** Switch for the interpolation facility for string literals. */
     String INTERPOLATE_STRINGLITERALS = "runtime.interpolate_string_literals";
 
-    /** Switch for the immutability of integer ranges. */
+    /**
+     * Switch for the immutability of integer ranges.
+     * @deprecated since 2.5: ranges will always be immutable in the next major version
+     */
+    @Deprecated
     String IMMUTABLE_RANGES = "runtime.immutable_ranges";
 
     /** Whether to warn about deprecated VTL syntax constructs (on by default). */
diff --git a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeInstance.java b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeInstance.java
index ae8efd59..8e348b36 100644
--- a/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeInstance.java
+++ b/velocity-engine-core/src/main/java/org/apache/velocity/runtime/RuntimeInstance.java
@@ -430,6 +430,11 @@ private void warnDeprecatedSettings()
         {
             log.warn("the '{}' setting is deprecated without replacement: the next major version does not provide this compatibility mode", VM_ENABLE_BC_MODE);
         }
+
+        if (!getBoolean(IMMUTABLE_RANGES, true))
+        {
+            log.warn("{} is false: mutable integer ranges are deprecated, ranges will always be immutable in the next major version", IMMUTABLE_RANGES);
+        }
     }
 
     private char getConfiguredCharacter(String configKey, char defaultChar)
diff --git a/velocity-engine-core/src/test/java/org/apache/velocity/test/DeprecationWarningTestCase.java b/velocity-engine-core/src/test/java/org/apache/velocity/test/DeprecationWarningTestCase.java
index 4f45d30f..1264f290 100644
--- a/velocity-engine-core/src/test/java/org/apache/velocity/test/DeprecationWarningTestCase.java
+++ b/velocity-engine-core/src/test/java/org/apache/velocity/test/DeprecationWarningTestCase.java
@@ -40,6 +40,7 @@
  * <ul>
  *   <li>{@code velocimacro.enable_bc_mode}</li>
  *   <li>an implicitly loaded macro library</li>
+ *   <li>{@code runtime.immutable_ranges = false}</li>
  * </ul>
  */
 public class DeprecationWarningTestCase extends BaseTestCase
@@ -554,4 +555,23 @@ public void testOldDefaultMacroLibrarySilentWhenDeprecationOff()
                     out.contains(OLD_DEFAULT_LIBRARY));
     }
 
+
+    /* ---- runtime.immutable_ranges = false: deprecated, ranges are always immutable ---- */
+
+    public void testMutableRangesWarn()
+    {
+        assertWarnsAtInit(RuntimeConstants.IMMUTABLE_RANGES, true, RuntimeConstants.IMMUTABLE_RANGES, "false");
+    }
+
+    public void testImmutableRangesSilent()
+    {
+        assertSilentAtInit(RuntimeConstants.IMMUTABLE_RANGES, true, RuntimeConstants.IMMUTABLE_RANGES, "true");
+        assertSilentAtInit(RuntimeConstants.IMMUTABLE_RANGES, true, null, null);
+    }
+
+    public void testMutableRangesSilentWhenDeprecationOff()
+    {
+        assertSilentAtInit(RuntimeConstants.IMMUTABLE_RANGES, false, RuntimeConstants.IMMUTABLE_RANGES, "false");
+    }
+
 }