diff --git a/CHANGES.md b/CHANGES.md
index 549a1ff55c..a55555b95e 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -20,12 +20,24 @@
- **Weblog templates have render limits.** A page stops rendering, with a
logged error, once it writes more than `rendering.maxOutputChars` (10 MB)
- or runs longer than `rendering.maxRenderSeconds` (30 seconds); `#foreach`
- stops at 100,000 passes, and `String.repeat` isn't available. `#parse` and
- `#include` load only the weblog's own templates, and macros defined inline
- in a template stay with the page that defines them and the templates it
- includes. Library macros stay global. Error pages no
- longer show template ids (#335).
+ or runs longer than `rendering.maxRenderSeconds` (30 seconds), and the
+ page isn't cached. The same happens to a `#foreach` of more than 100,000
+ passes, a render that builds more than ten times `maxOutputChars` of
+ strings in memory or adds more than 1,000,000 items to lists and maps, a
+ number past 100,000 bits, and a regular expression that repeats a part
+ that can match an empty string. `String.repeat`, `format`, `join`, `lines`
+ and `splitWithDelimiters` aren't available, nor are static methods called
+ through `$x.class`. `#parse` and `#include` load only the weblog's own
+ templates. Error pages no longer show template ids (#335).
+- **Macros defined in a template belong to that template.** A macro defined
+ inline in a template works in that page and in the templates it
+ `#parse`s, and one weblog's macro no longer replaces another's of the same
+ name. A custom theme that calls a macro defined in a different template,
+ which it doesn't `#parse`, now prints the call as text. Before, such a call
+ worked only once the defining template had been rendered since the server
+ started. Define the macro in the page that calls it, or `#parse` the
+ template that defines it. Library macros (`roller.vm`, `weblog.vm` and a
+ site's own `roller-custom.vm`) stay global (#335).
- **Entries with scripts or embeds open as HTML.** If an entry contains
scripts, frames, embedded objects, event-handler attributes or
diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java
new file mode 100644
index 0000000000..45c8ed84da
--- /dev/null
+++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java
@@ -0,0 +1,502 @@
+/*
+ * 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.
+ */
+
+package org.apache.roller.weblogger.ui.rendering.velocity;
+
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Runs the String methods that take a regular expression (matches,
+ * replaceAll, replaceFirst and split) over text that checks the render
+ * deadline as the expression reads it, so a slow expression stops with the
+ * render instead of holding the thread, and replaceAll and replaceFirst stop
+ * at the output limit as they build the result. Each gives the same result
+ * as the String method; see String's documentation for the Pattern call each
+ * one is equivalent to.
+ *
+ *
An expression can also backtrack without reading the text, when parts
+ * of it can match an empty string in more than one way, and then the
+ * deadline is never checked. checkPattern refuses the usual forms of that
+ * before the expression runs.
+ */
+final class DeadlineRegex {
+
+ /** Returned when the call isn't one of these methods. */
+ static final Object NOT_HANDLED = new Object();
+
+ private DeadlineRegex() {
+ }
+
+ /**
+ * @return the result of the call, or NOT_HANDLED when it isn't one of
+ * these methods or its arguments don't fit them
+ */
+ static Object invoke(String s, String methodName, Object[] args) {
+ if (args == null || args.length == 0 || args.length > 2 || args[0] == null) {
+ return NOT_HANDLED;
+ }
+ // the arguments already have the method's parameter types: Velocity
+ // finds no method for a call whose arguments don't fit
+ String regex = args[0].toString();
+ Object second = args.length > 1 ? args[1] : null;
+ CharSequence text = new DeadlineText(s);
+ switch (methodName) {
+ case "matches":
+ return args.length == 1 ? compile(regex).matcher(text).matches()
+ : NOT_HANDLED;
+ case "replaceAll":
+ case "replaceFirst":
+ return args.length == 2 ? replace(s, compile(regex).matcher(text),
+ second == null ? null : second.toString(),
+ "replaceAll".equals(methodName)) : NOT_HANDLED;
+ case "split":
+ Integer limit = args.length == 1 ? Integer.valueOf(0) : toInt(second);
+ if (limit == null) {
+ return NOT_HANDLED;
+ }
+ return split(s, compile(regex).matcher(text), limit);
+ default:
+ return NOT_HANDLED;
+ }
+ }
+
+ /** No more pieces than a #foreach can visit (directive.foreach.max_loops). */
+ static final int MAX_SPLIT_PIECES = 100_000;
+
+ /**
+ * Pattern.split, throwing if it would return more than MAX_SPLIT_PIECES.
+ * With a limit of 0 split drops trailing empty pieces, so those are
+ * neither counted nor allocated: empty pieces are only added once a piece
+ * that isn't empty follows them.
+ */
+ private static String[] split(String s, Matcher m, int limit) {
+ List pieces = new ArrayList<>();
+ int heldBack = 0;
+ int index = 0;
+ boolean last = false;
+ while (!last) {
+ last = limit > 0 && pieces.size() + heldBack == limit - 1 || !m.find();
+ if (!last && m.end() == 0) {
+ // an empty match at the start doesn't make an empty first piece
+ continue;
+ }
+ if (last && index == 0) {
+ // a string with no match is returned whole, even when empty
+ return new String[] {s};
+ }
+ int end = last ? s.length() : m.start();
+ if (limit == 0 && end == index) {
+ heldBack++;
+ } else {
+ if (pieces.size() + heldBack >= MAX_SPLIT_PIECES) {
+ throw new RenderLimitException("split produced more than "
+ + MAX_SPLIT_PIECES + " pieces");
+ }
+ for (; heldBack > 0; heldBack--) {
+ pieces.add("");
+ }
+ pieces.add(s.substring(index, end));
+ }
+ index = last ? end : m.end();
+ }
+ return pieces.toArray(new String[0]);
+ }
+
+ private static Integer toInt(Object value) {
+ return value instanceof Number ? Integer.valueOf(((Number) value).intValue()) : null;
+ }
+
+ /**
+ * Matcher.replaceAll and replaceFirst, checking before each replacement,
+ * and before the text after the last one, that it can't take the result
+ * past the output limit: a replacement adds its own length plus the
+ * length of each group it refers to ($1, ${name}) in that match.
+ */
+ private static String replace(String s, Matcher m, String replacement, boolean all) {
+ if (replacement == null) {
+ // as Matcher does: replaceFirst refuses null at once, and
+ // replaceAll only once there is something to replace
+ if (!all || m.find()) {
+ throw new NullPointerException("replacement");
+ }
+ return s;
+ }
+ List references = groupReferences(replacement, m.groupCount());
+ StringBuilder out = new StringBuilder();
+ int previousEnd = 0;
+ while (m.find()) {
+ long grown = replacement.length();
+ for (Object reference : references) {
+ grown += groupLength(m, reference);
+ }
+ RenderSession.checkLength((long) out.length() + (m.start() - previousEnd) + grown);
+ m.appendReplacement(out, replacement);
+ previousEnd = m.end();
+ if (!all) {
+ break;
+ }
+ }
+ // the text after the last replacement is copied as it is
+ RenderSession.checkLength((long) out.length() + (m.regionEnd() - previousEnd));
+ m.appendTail(out);
+ return out.toString();
+ }
+
+ /**
+ * @return the groups a replacement refers to, as group numbers and names,
+ * read the way Matcher.appendReplacement reads them. A reference
+ * it would refuse ends the list; appendReplacement then throws.
+ */
+ private static List groupReferences(String replacement, int groupCount) {
+ List references = new ArrayList<>();
+ int i = 0;
+ int n = replacement.length();
+ while (i < n) {
+ char c = replacement.charAt(i++);
+ if (c == '\\') {
+ i++;
+ } else if (c == '$') {
+ if (i >= n) {
+ break;
+ }
+ if (replacement.charAt(i) == '{') {
+ int close = replacement.indexOf('}', i);
+ if (close < 0) {
+ break;
+ }
+ references.add(replacement.substring(i + 1, close));
+ i = close + 1;
+ } else {
+ int group = replacement.charAt(i) - '0';
+ if (group < 0 || group > 9) {
+ break;
+ }
+ // more digits are read while they name a group that exists
+ for (i++; i < n; i++) {
+ int digit = replacement.charAt(i) - '0';
+ if (digit < 0 || digit > 9 || group * 10 + digit > groupCount) {
+ break;
+ }
+ group = group * 10 + digit;
+ }
+ references.add(group);
+ }
+ }
+ }
+ return references;
+ }
+
+ private static long groupLength(Matcher m, Object reference) {
+ try {
+ int start = reference instanceof Integer ? m.start((Integer) reference)
+ : m.start((String) reference);
+ int end = reference instanceof Integer ? m.end((Integer) reference)
+ : m.end((String) reference);
+ return start < 0 ? 0 : end - start;
+ } catch (IndexOutOfBoundsException | IllegalArgumentException ex) {
+ // appendReplacement throws for a group that doesn't exist
+ return 0;
+ }
+ }
+
+ private static Pattern compile(String regex) {
+ checkPattern(regex);
+ return Pattern.compile(regex);
+ }
+
+ /**
+ * Throws if part of the expression can match an empty string in more
+ * than one way at the same place: a group or assertion that can match
+ * empty followed by a quantifier, or a group with two alternatives that
+ * can. Matching such an expression can try exponentially many ways
+ * without reading a character, so DeadlineText never gets to check the
+ * deadline. See canMatchEmpty for how a part is tried.
+ */
+ static void checkPattern(String regex) {
+ // for each open group: where its body and its current alternative
+ // start, how many of its alternatives can match empty, and whether
+ // it is a lookaround, which matches empty whatever it contains
+ Deque groups = new ArrayDeque<>();
+ int n = regex.length();
+ int i = 0;
+ while (i < n) {
+ char c = regex.charAt(i);
+ if (c == '\\') {
+ i = skipEscape(regex, i);
+ } else if (c == '[') {
+ i = skipClass(regex, i);
+ } else if (c == '^' || c == '$') {
+ i++;
+ refuseQuantifier(regex, i);
+ } else if (c == '(') {
+ int[] group = openGroup(regex, i);
+ if (group == null) {
+ // flags such as (?i), which apply to the rest of the group
+ i = regex.indexOf(')', i) + 1;
+ if (i == 0) {
+ return;
+ }
+ } else {
+ groups.push(group);
+ i = group[0];
+ }
+ } else if (c == '|' && !groups.isEmpty()) {
+ int[] group = groups.peek();
+ if (canMatchEmpty(regex.substring(group[1], i))) {
+ group[2]++;
+ }
+ group[1] = ++i;
+ } else if (c == ')' && !groups.isEmpty()) {
+ int[] group = groups.pop();
+ boolean alternatives = group[1] != group[0];
+ if (alternatives && canMatchEmpty(regex.substring(group[1], i))) {
+ group[2]++;
+ }
+ if (group[2] > 1) {
+ throw refused();
+ }
+ boolean empty = group[3] == 1 || canMatchEmpty(regex.substring(group[0], i));
+ i++;
+ if (empty) {
+ refuseQuantifier(regex, i);
+ }
+ } else {
+ i++;
+ }
+ }
+ }
+
+ /**
+ * @return true if part of an expression can match an empty string.
+ * Lookarounds, anchors and boundaries match empty somewhere
+ * whatever they test, so they are taken out first, and the part
+ * is tried with and without comments mode, which an inline (?x)
+ * may have turned on. A part that doesn't compile on its own
+ * counts as one that can.
+ */
+ private static boolean canMatchEmpty(String part) {
+ String rest = withoutZeroWidth(part);
+ try {
+ return Pattern.compile(rest).matcher("").matches()
+ || Pattern.compile(rest, Pattern.COMMENTS).matcher("").matches();
+ } catch (RuntimeException ex) {
+ return true;
+ }
+ }
+
+ /** @return the part with its lookarounds, anchors and boundaries taken out */
+ private static String withoutZeroWidth(String part) {
+ StringBuilder out = new StringBuilder();
+ int n = part.length();
+ int i = 0;
+ while (i < n) {
+ char c = part.charAt(i);
+ if (c == '\\') {
+ char e = i + 1 < n ? part.charAt(i + 1) : 0;
+ int end = e == 'Q' ? skipEscape(part, i) : Math.min(i + 2, n);
+ if ("bBAGzZ".indexOf(e) < 0 || e == 0) {
+ out.append(part, i, end);
+ }
+ i = end;
+ } else if (c == '[') {
+ int end = skipClass(part, i);
+ out.append(part, i, end);
+ i = end;
+ } else if (c == '^' || c == '$') {
+ i++;
+ } else if (c == '(' && isLookaround(part, i)) {
+ out.append("(?:)");
+ i = closingParen(part, i) + 1;
+ } else {
+ out.append(c);
+ i++;
+ }
+ }
+ return out.toString();
+ }
+
+ private static boolean isLookaround(String regex, int i) {
+ return regex.startsWith("(?=", i) || regex.startsWith("(?!", i)
+ || regex.startsWith("(?<=", i) || regex.startsWith("(?= regex.length() || regex.charAt(i) != '?') {
+ return new int[] {i, i, 0, 0};
+ }
+ i++;
+ char c = i < regex.length() ? regex.charAt(i) : 0;
+ char next = i + 1 < regex.length() ? regex.charAt(i + 1) : 0;
+ if (c == '=' || c == '!') {
+ return new int[] {i + 1, i + 1, 0, 1};
+ }
+ if (c == '<' && (next == '=' || next == '!')) {
+ return new int[] {i + 2, i + 2, 0, 1};
+ }
+ if (c == '<') {
+ int body = regex.indexOf('>', i) + 1;
+ body = body == 0 ? regex.length() : body;
+ return new int[] {body, body, 0, 0};
+ }
+ if (c == ':' || c == '>') {
+ return new int[] {i + 1, i + 1, 0, 0};
+ }
+ while (i < regex.length() && (Character.isLetter(regex.charAt(i))
+ || regex.charAt(i) == '-')) {
+ i++;
+ }
+ if (i < regex.length() && regex.charAt(i) == ':') {
+ return new int[] {i + 1, i + 1, 0, 0};
+ }
+ return null;
+ }
+
+ /** @return the index after the escape at i; a quantified backreference or boundary is refused */
+ private static int skipEscape(String regex, int i) {
+ char c = i + 1 < regex.length() ? regex.charAt(i + 1) : 0;
+ if (c == 'Q') {
+ int end = regex.indexOf("\\E", i + 2);
+ return end < 0 ? regex.length() : end + 2;
+ }
+ int end = Math.min(i + 2, regex.length());
+ if (c == 'k') {
+ int close = regex.indexOf('>', i);
+ end = close < 0 ? regex.length() : close + 1;
+ } else if (c >= '1' && c <= '9') {
+ while (end < regex.length() && Character.isDigit(regex.charAt(end))) {
+ end++;
+ }
+ } else if ("bBAGzZ".indexOf(c) < 0 || c == 0) {
+ return end;
+ }
+ // a backreference can match empty, and boundaries always do
+ refuseQuantifier(regex, end);
+ return end;
+ }
+
+ /** @return the index after the character class that opens at i */
+ private static int skipClass(String regex, int i) {
+ int depth = 0;
+ int n = regex.length();
+ while (i < n) {
+ char c = regex.charAt(i);
+ if (c == '\\') {
+ i += 2;
+ continue;
+ }
+ if (c == '[') {
+ depth++;
+ i++;
+ // a ']' first in a class, after any '^', is a plain character
+ if (i < n && regex.charAt(i) == '^') {
+ i++;
+ }
+ if (i < n && regex.charAt(i) == ']') {
+ i++;
+ }
+ continue;
+ }
+ i++;
+ if (c == ']' && --depth == 0) {
+ return i;
+ }
+ }
+ return n;
+ }
+
+ private static void refuseQuantifier(String regex, int i) {
+ if (i < regex.length() && "?*+{".indexOf(regex.charAt(i)) >= 0) {
+ throw refused();
+ }
+ }
+
+ private static RenderLimitException refused() {
+ return new RenderLimitException("a regular expression repeats a part that"
+ + " can match an empty string");
+ }
+
+ /** A string that checks the deadline every few thousand character reads. */
+ private static final class DeadlineText implements CharSequence {
+
+ private final String s;
+ private int reads = 0;
+
+ DeadlineText(String s) {
+ this.s = s;
+ }
+
+ @Override
+ public char charAt(int index) {
+ if ((++reads & 0xfff) == 0) {
+ RenderSession.checkDeadline();
+ }
+ return s.charAt(index);
+ }
+
+ @Override
+ public int length() {
+ return s.length();
+ }
+
+ @Override
+ public CharSequence subSequence(int start, int end) {
+ return s.subSequence(start, end);
+ }
+
+ @Override
+ public String toString() {
+ return s;
+ }
+ }
+}
diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitException.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitException.java
new file mode 100644
index 0000000000..06d6ff4a2c
--- /dev/null
+++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitException.java
@@ -0,0 +1,34 @@
+/*
+ * 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.
+ */
+
+package org.apache.roller.weblogger.ui.rendering.velocity;
+
+/**
+ * Raised when a template goes past the size or time Roller allows for one
+ * render. It is unchecked so it passes through Velocity's directives and
+ * introspection unchanged; VelocityRenderer turns it into a failed render.
+ */
+public class RenderLimitException extends RuntimeException {
+
+ private static final long serialVersionUID = 1L;
+
+ public RenderLimitException(String message) {
+ super(message);
+ }
+}
diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitInsertionHandler.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitInsertionHandler.java
new file mode 100644
index 0000000000..6d4484817a
--- /dev/null
+++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitInsertionHandler.java
@@ -0,0 +1,44 @@
+/*
+ * 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.
+ */
+
+package org.apache.roller.weblogger.ui.rendering.velocity;
+
+import org.apache.velocity.app.event.ReferenceInsertionEventHandler;
+import org.apache.velocity.context.Context;
+
+/**
+ * Checks every value a template inserts, including into a string literal such
+ * as "$s$s", so a string built up in memory stops at the output limit before
+ * it is ever written.
+ */
+public class RenderLimitInsertionHandler implements ReferenceInsertionEventHandler {
+
+ @Override
+ public Object referenceInsert(Context context, String reference, Object value) {
+ RenderSession.checkDeadline();
+ RenderSession session = RenderSession.current();
+ if (value instanceof CharSequence) {
+ RenderSession.checkLength(((CharSequence) value).length());
+ } else if (session != null && ValueLimits.holdsValues(value)) {
+ // a list or map is written as text, built in full before it is written
+ RenderSession.checkLength(ValueLimits.textLength(value, session.getMaxOutputChars()));
+ }
+ return value;
+ }
+}
diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitParser.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitParser.java
new file mode 100644
index 0000000000..0af3a464c5
--- /dev/null
+++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitParser.java
@@ -0,0 +1,338 @@
+/*
+ * 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.
+ */
+
+package org.apache.roller.weblogger.ui.rendering.velocity;
+
+import java.io.IOException;
+import java.io.Reader;
+import java.io.Writer;
+import java.lang.reflect.Field;
+
+import org.apache.velocity.Template;
+import org.apache.velocity.context.InternalContextAdapter;
+import org.apache.velocity.runtime.RuntimeServices;
+import org.apache.velocity.runtime.parser.ParseException;
+import org.apache.velocity.runtime.parser.Parser;
+import org.apache.velocity.runtime.parser.StandardParser;
+import org.apache.velocity.runtime.parser.node.ASTAddNode;
+import org.apache.velocity.runtime.parser.node.ASTBlock;
+import org.apache.velocity.runtime.parser.node.ASTEQNode;
+import org.apache.velocity.runtime.parser.node.ASTMulNode;
+import org.apache.velocity.runtime.parser.node.ASTNENode;
+import org.apache.velocity.runtime.parser.node.ASTprocess;
+import org.apache.velocity.runtime.parser.node.Node;
+import org.apache.velocity.runtime.parser.node.SimpleNode;
+
+/**
+ * Velocity builds some strings in memory rather than in the output: string
+ * literals such as "$a$b", the + operator, and #define blocks or macro bodies
+ * used as strings. This parser, set as parser.class in velocity.properties,
+ * swaps the nodes that do so for ones that stop at the output limit while the
+ * string is built:
+ *
+ *
+ * a template's root node and every block (the body of #if, #foreach,
+ * #define, #macro and so on) count what they write into any writer that isn't
+ * already counted, such as the buffer of a string literal;
+ * + checks the length of two strings before joining them;
+ * == and != check the length of a list or map before comparing it with
+ * a string as text;
+ * * checks the size of two big numbers before multiplying them.
+ *
+ *
+ * The strings they build count toward the render's budget (RenderSession).
+ *
+ *
The nodes keep no state of their own between renders, so a parsed
+ * template is still safe to share between threads.
+ */
+public class RenderLimitParser extends StandardParser {
+
+ public RenderLimitParser(RuntimeServices rs) {
+ super(rs);
+ }
+
+ @Override
+ public SimpleNode parse(Reader reader, Template template) throws ParseException {
+ SimpleNode root = super.parse(reader, template);
+ if (root == null) {
+ return null;
+ }
+ SimpleNode limited = root.getClass() == ASTprocess.class
+ ? new LimitedProcess(this, (ASTprocess) root) : root;
+ limitChildren(limited);
+ return limited;
+ }
+
+ private void limitChildren(Node node) {
+ for (int i = 0; i < node.jjtGetNumChildren(); i++) {
+ Node child = node.jjtGetChild(i);
+ Node limited = child;
+ if (child.getClass() == ASTBlock.class) {
+ limited = new LimitedBlock(this, (ASTBlock) child);
+ } else if (child.getClass() == ASTAddNode.class) {
+ limited = new LimitedAddNode(this, (ASTAddNode) child);
+ } else if (child.getClass() == ASTEQNode.class) {
+ limited = new LimitedEQNode(this, (ASTEQNode) child);
+ } else if (child.getClass() == ASTNENode.class) {
+ limited = new LimitedNENode(this, (ASTNENode) child);
+ } else if (child.getClass() == ASTMulNode.class) {
+ limited = new LimitedMulNode(this, (ASTMulNode) child);
+ }
+ if (limited != child) {
+ node.jjtAddChild(limited, i);
+ limited.jjtSetParent(node);
+ }
+ limitChildren(limited);
+ }
+ }
+
+ /**
+ * Moves the children and source position of a parsed node to its
+ * replacement. The replacement's constructor copies the fields only a
+ * subclass can set: the last token and the template, which the parser no
+ * longer has once parsing is over and Velocity needs to say where in a
+ * template something went wrong.
+ */
+ private static void moveChildren(SimpleNode from, SimpleNode to) {
+ to.setFirstToken(from.getFirstToken());
+ to.setInfo(from.getInfo());
+ if (from.isInvalid()) {
+ to.setInvalid();
+ }
+ // last child first, so the child array is allocated once
+ for (int i = from.jjtGetNumChildren() - 1; i >= 0; i--) {
+ Node child = from.jjtGetChild(i);
+ to.jjtAddChild(child, i);
+ child.jjtSetParent(to);
+ }
+ }
+
+ /**
+ * @return the writer to render into: the same writer when it already
+ * counts toward the output limit, otherwise one that counts what
+ * this render writes into it
+ */
+ static Writer limited(Writer writer) {
+ if (writer instanceof RenderLimitWriter || writer instanceof CountingWriter
+ || RenderSession.current() == null) {
+ return writer;
+ }
+ return new CountingWriter(writer);
+ }
+
+ /** Counts what one render writes into a buffer such as a string literal's. */
+ static final class CountingWriter extends Writer {
+
+ private final Writer out;
+ private long written = 0;
+
+ CountingWriter(Writer out) {
+ this.out = out;
+ }
+
+ private void count(long len) {
+ written += len;
+ RenderSession.checkLength(written);
+ RenderSession.chargeBuilt(len);
+ RenderSession.checkDeadline();
+ }
+
+ @Override
+ public void write(int c) throws IOException {
+ count(1);
+ out.write(c);
+ }
+
+ @Override
+ public void write(char[] cbuf, int off, int len) throws IOException {
+ count(len);
+ out.write(cbuf, off, len);
+ }
+
+ @Override
+ public void write(String str, int off, int len) throws IOException {
+ count(len);
+ out.write(str, off, len);
+ }
+
+ @Override
+ public void flush() throws IOException {
+ out.flush();
+ }
+
+ @Override
+ public void close() throws IOException {
+ out.close();
+ }
+ }
+
+ static final class LimitedProcess extends ASTprocess {
+
+ LimitedProcess(Parser parser, ASTprocess from) {
+ super(parser, from.getType());
+ moveChildren(from, this);
+ this.last = from.getLastToken();
+ this.template = from.getTemplate();
+ }
+
+ @Override
+ public boolean render(InternalContextAdapter context, Writer writer) throws IOException {
+ return super.render(context, limited(writer));
+ }
+ }
+
+ static final class LimitedBlock extends ASTBlock {
+
+ // ASTBlock has no getter for the whitespace the parser keeps after it
+ private static final Field MORE_POSTFIX;
+
+ static {
+ try {
+ MORE_POSTFIX = ASTBlock.class.getDeclaredField("morePostfix");
+ MORE_POSTFIX.setAccessible(true);
+ } catch (NoSuchFieldException ex) {
+ throw new IllegalStateException(
+ "this Velocity version's ASTBlock has no morePostfix field", ex);
+ }
+ }
+
+ LimitedBlock(Parser parser, ASTBlock from) {
+ super(parser, from.getType());
+ moveChildren(from, this);
+ this.last = from.getLastToken();
+ this.template = from.getTemplate();
+ setPrefix(from.getPrefix());
+ setPostfix(from.getPostfix());
+ endsWithNewline = from.endsWithNewline;
+ try {
+ setMorePostfix((String) MORE_POSTFIX.get(from));
+ } catch (IllegalAccessException ex) {
+ throw new IllegalStateException(ex);
+ }
+ }
+
+ @Override
+ public boolean render(InternalContextAdapter context, Writer writer) throws IOException {
+ return super.render(context, limited(writer));
+ }
+ }
+
+ static final class LimitedAddNode extends ASTAddNode {
+
+ LimitedAddNode(Parser parser, ASTAddNode from) {
+ super(parser, from.getType());
+ moveChildren(from, this);
+ this.last = from.getLastToken();
+ this.template = from.getTemplate();
+ }
+
+ @Override
+ protected Object handleSpecial(Object left, Object right, InternalContextAdapter context) {
+ if (left instanceof CharSequence || right instanceof CharSequence) {
+ RenderSession.checkLength(textLength(left) + textLength(right));
+ }
+ Object result = super.handleSpecial(left, right, context);
+ if (result instanceof CharSequence) {
+ RenderSession.checkLength(((CharSequence) result).length());
+ RenderSession.chargeBuilt(((CharSequence) result).length());
+ }
+ return result;
+ }
+
+ @Override
+ public Number perform(Number left, Number right, InternalContextAdapter context) {
+ Number result = super.perform(left, right, context);
+ ValueLimits.checkResult(result);
+ return result;
+ }
+ }
+
+ /**
+ * @return the length of a string, or of the text of a list or map, that
+ * Velocity is about to build; 0 for other values, whose text is
+ * short or checked once it is built
+ */
+ private static long textLength(Object value) {
+ RenderSession session = RenderSession.current();
+ if (session == null) {
+ return 0;
+ }
+ if (value instanceof CharSequence || ValueLimits.holdsValues(value)) {
+ return ValueLimits.textLength(value, session.getMaxOutputChars());
+ }
+ return 0;
+ }
+
+ /** Checks the text of a list or map before == compares it with a string. */
+ private static void checkComparedText(Object left, Object right) {
+ if (!left.getClass().isAssignableFrom(right.getClass())
+ && !right.getClass().isAssignableFrom(left.getClass())) {
+ RenderSession.checkLength(textLength(left));
+ RenderSession.checkLength(textLength(right));
+ }
+ }
+
+ static final class LimitedEQNode extends ASTEQNode {
+
+ LimitedEQNode(Parser parser, ASTEQNode from) {
+ super(parser, from.getType());
+ moveChildren(from, this);
+ this.last = from.getLastToken();
+ this.template = from.getTemplate();
+ }
+
+ @Override
+ public boolean compareNonNumber(Object left, Object right) {
+ checkComparedText(left, right);
+ return super.compareNonNumber(left, right);
+ }
+ }
+
+ static final class LimitedNENode extends ASTNENode {
+
+ LimitedNENode(Parser parser, ASTNENode from) {
+ super(parser, from.getType());
+ moveChildren(from, this);
+ this.last = from.getLastToken();
+ this.template = from.getTemplate();
+ }
+
+ @Override
+ public boolean compareNonNumber(Object left, Object right) {
+ checkComparedText(left, right);
+ return super.compareNonNumber(left, right);
+ }
+ }
+
+ static final class LimitedMulNode extends ASTMulNode {
+
+ LimitedMulNode(Parser parser, ASTMulNode from) {
+ super(parser, from.getType());
+ moveChildren(from, this);
+ this.last = from.getLastToken();
+ this.template = from.getTemplate();
+ }
+
+ @Override
+ public Number perform(Number left, Number right, InternalContextAdapter context) {
+ ValueLimits.checkBits(ValueLimits.bits(left) + ValueLimits.bits(right));
+ return super.perform(left, right, context);
+ }
+ }
+}
diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitUberspector.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitUberspector.java
new file mode 100644
index 0000000000..ac833a687c
--- /dev/null
+++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitUberspector.java
@@ -0,0 +1,194 @@
+/*
+ * 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.
+ */
+
+package org.apache.roller.weblogger.ui.rendering.velocity;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.Map;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.roller.weblogger.ui.rendering.model.UtilitiesModel;
+import org.apache.velocity.util.introspection.AbstractChainableUberspector;
+import org.apache.velocity.util.introspection.Info;
+import org.apache.velocity.util.introspection.VelMethod;
+import org.apache.velocity.util.introspection.VelPropertyGet;
+
+/**
+ * Chained after SecureUberspector, this keeps method calls from templates
+ * inside the render limits: each call and property read checks the deadline,
+ * a string a call returns may be no longer than the output limit, a call that
+ * could build a longer string is stopped before it runs, and string methods
+ * whose result can't be bounded from the call (String.repeat, String.format
+ * and others; see StringGrowth) are not offered. Regular expressions given to
+ * String methods check the deadline as they run; see DeadlineRegex.
+ */
+public class RenderLimitUberspector extends AbstractChainableUberspector {
+
+ private static final Log LOG = LogFactory.getLog(RenderLimitUberspector.class);
+
+ @Override
+ public Iterator getIterator(Object obj, Info i) {
+ RenderSession.checkDeadline();
+ return super.getIterator(obj, i);
+ }
+
+ @Override
+ public VelMethod getMethod(Object obj, String methodName, Object[] args, Info i) {
+ VelMethod method = super.getMethod(obj, methodName, args, i);
+ if (method == null) {
+ return null;
+ }
+ if (StringGrowth.isRefused(obj, methodName, method.getReturnType())) {
+ LOG.debug("Refusing " + obj.getClass().getSimpleName() + "." + methodName
+ + " at " + i);
+ return null;
+ }
+ return new LimitedMethod(method);
+ }
+
+ @Override
+ public VelPropertyGet getPropertyGet(Object obj, String identifier, Info i) {
+ VelPropertyGet getter = super.getPropertyGet(obj, identifier, i);
+ return getter == null ? null : new LimitedPropertyGet(getter);
+ }
+
+ private static Object checked(Object result) {
+ if (result instanceof CharSequence) {
+ RenderSession.checkLength(((CharSequence) result).length());
+ }
+ return result;
+ }
+
+ private static final class LimitedMethod implements VelMethod {
+
+ private final VelMethod method;
+
+ LimitedMethod(VelMethod method) {
+ this.method = method;
+ }
+
+ @Override
+ public Object invoke(Object o, Object[] params)
+ throws IllegalAccessException, InvocationTargetException {
+ RenderSession.checkDeadline();
+ RenderSession session = RenderSession.current();
+ if (session == null) {
+ return method.invoke(o, params);
+ }
+ String name = method.getMethodName();
+ Object[] args = params == null ? new Object[0] : params;
+
+ // before the call: what it can build or take has to fit
+ RenderSession.checkLength(StringGrowth.maxResultLength(o, name, args));
+ StringGrowth.checkPieces(o, name, args);
+ ValueLimits.checkNumberCall(o, name, args);
+ boolean container = o instanceof Collection || o instanceof Map;
+ if (container) {
+ ValueLimits.checkContainerCall(o, name, args, session.getMaxOutputChars());
+ }
+ long sizeBefore = ValueLimits.size(o);
+ boolean builder = o instanceof StringBuilder || o instanceof StringBuffer;
+ long lengthBefore = builder ? ((CharSequence) o).length() : 0;
+
+ Object result = DeadlineRegex.NOT_HANDLED;
+ if (o instanceof String) {
+ try {
+ result = DeadlineRegex.invoke((String) o, name, args);
+ } catch (RenderLimitException ex) {
+ throw ex;
+ } catch (RuntimeException ex) {
+ // reported as a template error, as the String method's own is
+ throw new InvocationTargetException(ex);
+ }
+ }
+ if (result == DeadlineRegex.NOT_HANDLED) {
+ result = method.invoke(o, params);
+ }
+
+ // after the call: count what it built toward the render's budget
+ checked(result);
+ ValueLimits.checkResult(result);
+ if (container) {
+ RenderSession.chargeItems(ValueLimits.size(o) - sizeBefore);
+ if (ValueLimits.isCopy(name)) {
+ RenderSession.chargeItems(result instanceof Object[]
+ ? ((Object[]) result).length : ValueLimits.size(result));
+ }
+ } else if (builder) {
+ RenderSession.chargeBuilt(((CharSequence) o).length() - lengthBefore);
+ } else if (o instanceof String || o instanceof UtilitiesModel) {
+ if (result instanceof CharSequence && result != o) {
+ RenderSession.chargeBuilt(((CharSequence) result).length());
+ } else if (result instanceof Object[]) {
+ RenderSession.chargeItems(((Object[]) result).length);
+ }
+ }
+ return result;
+ }
+
+ @Override
+ public boolean isCacheable() {
+ return method.isCacheable();
+ }
+
+ @Override
+ public String getMethodName() {
+ return method.getMethodName();
+ }
+
+ @Override
+ public Method getMethod() {
+ return method.getMethod();
+ }
+
+ @Override
+ public Class> getReturnType() {
+ return method.getReturnType();
+ }
+ }
+
+ private static final class LimitedPropertyGet implements VelPropertyGet {
+
+ private final VelPropertyGet getter;
+
+ LimitedPropertyGet(VelPropertyGet getter) {
+ this.getter = getter;
+ }
+
+ @Override
+ public Object invoke(Object o) throws Exception {
+ RenderSession.checkDeadline();
+ return checked(getter.invoke(o));
+ }
+
+ @Override
+ public boolean isCacheable() {
+ return getter.isCacheable();
+ }
+
+ @Override
+ public String getMethodName() {
+ return getter.getMethodName();
+ }
+ }
+}
diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitWriter.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitWriter.java
new file mode 100644
index 0000000000..812a4281b1
--- /dev/null
+++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitWriter.java
@@ -0,0 +1,76 @@
+/*
+ * 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.
+ */
+
+package org.apache.roller.weblogger.ui.rendering.velocity;
+
+import java.io.IOException;
+import java.io.Writer;
+
+/**
+ * Passes rendered output through, failing the render once it has written more
+ * than the session allows or run past its deadline.
+ */
+class RenderLimitWriter extends Writer {
+
+ private final Writer out;
+ private final long maxChars;
+ private long written = 0;
+
+ RenderLimitWriter(Writer out, RenderSession session) {
+ this.out = out;
+ this.maxChars = session.getMaxOutputChars();
+ }
+
+ private void count(long len) {
+ written += len;
+ if (written > maxChars) {
+ throw new RenderLimitException("rendering produced more than "
+ + maxChars + " characters");
+ }
+ RenderSession.checkDeadline();
+ }
+
+ @Override
+ public void write(int c) throws IOException {
+ count(1);
+ out.write(c);
+ }
+
+ @Override
+ public void write(char[] cbuf, int off, int len) throws IOException {
+ count(len);
+ out.write(cbuf, off, len);
+ }
+
+ @Override
+ public void write(String str, int off, int len) throws IOException {
+ count(len);
+ out.write(str, off, len);
+ }
+
+ @Override
+ public void flush() throws IOException {
+ out.flush();
+ }
+
+ @Override
+ public void close() throws IOException {
+ out.close();
+ }
+}
diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderSession.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderSession.java
new file mode 100644
index 0000000000..b21658a0d9
--- /dev/null
+++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderSession.java
@@ -0,0 +1,206 @@
+/*
+ * 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.
+ */
+
+package org.apache.roller.weblogger.ui.rendering.velocity;
+
+import java.util.concurrent.TimeUnit;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.roller.weblogger.config.WebloggerConfig;
+
+/**
+ * What applies while one template is rendered on this thread: the weblog whose
+ * stored templates it may load, and how much output and time it may use.
+ *
+ *
Weblog templates are written by weblog authors, so the engine's hooks
+ * (the resource loader, the output writer, #foreach, introspection and
+ * reference insertion) check the current session rather than trusting the
+ * template. Outside a session those hooks apply no limits.
+ *
+ *
Besides the output and time limits, a render has a budget for what it
+ * builds in memory: the characters of the strings it makes, and the items it
+ * adds to lists and maps. A template that keeps many strings or a long list
+ * never writes them, so the output limit alone doesn't stop it. A session
+ * started inside another one shares that one's time and budget.
+ */
+final class RenderSession {
+
+ private static final Log LOG = LogFactory.getLog(RenderSession.class);
+
+ /** Most characters one render may write, or put in one string. */
+ static final String MAX_OUTPUT_CHARS = "rendering.maxOutputChars";
+
+ /** Most seconds one render may take. */
+ static final String MAX_RENDER_SECONDS = "rendering.maxRenderSeconds";
+
+ private static final int DEFAULT_MAX_OUTPUT_CHARS = 10 * 1024 * 1024;
+ private static final int DEFAULT_MAX_RENDER_SECONDS = 30;
+
+ /** The characters of strings one render may build, as a multiple of the output limit. */
+ static final int BUILT_CHARS_PER_OUTPUT_CHAR = 10;
+
+ /** Most items one render may add to lists and maps, or get from split calls. */
+ static final long MAX_ITEMS = 1_000_000;
+
+ private static final ThreadLocal CURRENT = new ThreadLocal<>();
+
+ private final String weblogId;
+ private final Budget budget;
+ private final RenderSession previous;
+
+ /** What one render may use, shared by the sessions started inside it. */
+ private static final class Budget {
+ final long maxOutputChars;
+ final int maxRenderSeconds;
+ final long deadline;
+ final long maxBuiltChars;
+ final long maxItems;
+ long builtChars = 0;
+ long items = 0;
+
+ Budget() {
+ int chars = intProperty(MAX_OUTPUT_CHARS, DEFAULT_MAX_OUTPUT_CHARS);
+ maxOutputChars = chars > 0 ? chars : Long.MAX_VALUE;
+ maxBuiltChars = chars > 0 ? (long) chars * BUILT_CHARS_PER_OUTPUT_CHAR
+ : Long.MAX_VALUE;
+ maxItems = chars > 0 ? MAX_ITEMS : Long.MAX_VALUE;
+ maxRenderSeconds = intProperty(MAX_RENDER_SECONDS, DEFAULT_MAX_RENDER_SECONDS);
+ deadline = maxRenderSeconds > 0
+ ? System.nanoTime() + TimeUnit.SECONDS.toNanos(maxRenderSeconds)
+ : 0;
+ }
+ }
+
+ private RenderSession(String weblogId, RenderSession previous) {
+ this.weblogId = weblogId;
+ this.previous = previous;
+ this.budget = previous != null ? previous.budget : new Budget();
+ }
+
+ /** @return the property's value, or the default when it isn't a number */
+ private static int intProperty(String name, int defaultValue) {
+ String value = WebloggerConfig.getProperty(name);
+ if (value == null || value.isBlank()) {
+ return defaultValue;
+ }
+ try {
+ return Integer.parseInt(value.trim());
+ } catch (NumberFormatException ex) {
+ LOG.warn(name + " is not a number, using " + defaultValue + ": " + value);
+ return defaultValue;
+ }
+ }
+
+ /**
+ * Starts a session on this thread.
+ *
+ * @param weblogId the weblog being rendered, or null when there is none,
+ * in which case no stored weblog template may be loaded
+ */
+ static RenderSession begin(String weblogId) {
+ RenderSession session = new RenderSession(weblogId, CURRENT.get());
+ CURRENT.set(session);
+ return session;
+ }
+
+ /** Ends this session, restoring any session it was started inside. */
+ void end() {
+ if (previous == null) {
+ CURRENT.remove();
+ } else {
+ CURRENT.set(previous);
+ }
+ }
+
+ /** @return the session on this thread, or null outside rendering */
+ static RenderSession current() {
+ return CURRENT.get();
+ }
+
+ String getWeblogId() {
+ return weblogId;
+ }
+
+ long getMaxOutputChars() {
+ return budget.maxOutputChars;
+ }
+
+ /** Throws once the current render has used up its time. */
+ static void checkDeadline() {
+ RenderSession session = CURRENT.get();
+ if (session != null && session.budget.maxRenderSeconds > 0
+ && System.nanoTime() - session.budget.deadline > 0) {
+ throw new RenderLimitException("rendering took longer than "
+ + session.budget.maxRenderSeconds + " seconds");
+ }
+ }
+
+ /** Throws if one string would be longer than one render may write. */
+ static void checkLength(long length) {
+ RenderSession session = CURRENT.get();
+ if (session != null && length > session.budget.maxOutputChars) {
+ throw new RenderLimitException("a string would be longer than "
+ + session.budget.maxOutputChars + " characters");
+ }
+ }
+
+ /** Counts the characters of a string the render built. */
+ static void chargeBuilt(long chars) {
+ RenderSession session = CURRENT.get();
+ if (session != null && chars > 0) {
+ Budget b = session.budget;
+ b.builtChars = add(b.builtChars, chars);
+ if (b.builtChars > b.maxBuiltChars) {
+ throw new RenderLimitException("rendering built more than "
+ + b.maxBuiltChars + " characters of strings");
+ }
+ }
+ }
+
+ /** Throws, without counting them, if this many more items would be over the budget. */
+ static void checkItems(long count) {
+ RenderSession session = CURRENT.get();
+ if (session != null && add(session.budget.items, count) > session.budget.maxItems) {
+ throw itemsException(session.budget);
+ }
+ }
+
+ /** Counts items the render added to a list or map, or got from a split. */
+ static void chargeItems(long count) {
+ RenderSession session = CURRENT.get();
+ if (session != null && count > 0) {
+ Budget b = session.budget;
+ b.items = add(b.items, count);
+ if (b.items > b.maxItems) {
+ throw itemsException(b);
+ }
+ }
+ }
+
+ private static RenderLimitException itemsException(Budget b) {
+ return new RenderLimitException("rendering added more than "
+ + b.maxItems + " items to lists and maps");
+ }
+
+ private static long add(long a, long b) {
+ long sum = a + b;
+ return sum < 0 ? Long.MAX_VALUE : sum;
+ }
+}
diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerForeach.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerForeach.java
new file mode 100644
index 0000000000..b5cce131f6
--- /dev/null
+++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerForeach.java
@@ -0,0 +1,80 @@
+/*
+ * 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.
+ */
+
+package org.apache.roller.weblogger.ui.rendering.velocity;
+
+import java.io.IOException;
+import java.io.Writer;
+import java.util.Iterator;
+
+import org.apache.velocity.context.InternalContextAdapter;
+import org.apache.velocity.runtime.directive.Foreach;
+import org.apache.velocity.runtime.parser.node.Node;
+
+/**
+ * Velocity's #foreach, checking the render deadline on every pass so a loop
+ * that writes nothing still stops, and failing the render on a loop of more
+ * than MAX_PASSES passes. Velocity's own directive.foreach.max_loops ends the
+ * loop without an error, so a page cut short that way would be served and
+ * cached as if it were whole. Registered in velocity.properties under
+ * runtime.custom_directives, where it replaces the built-in directive.
+ */
+public class RollerForeach extends Foreach {
+
+ /** Most passes one #foreach may make. */
+ static final int MAX_PASSES = 100_000;
+
+ @Override
+ protected Iterator getIterator(Object iterable, Node node) {
+ Iterator> items = super.getIterator(iterable, node);
+ return items == null || RenderSession.current() == null ? items : new Limited(items);
+ }
+
+ @Override
+ protected void renderBlock(InternalContextAdapter context, Writer writer, Node block)
+ throws IOException {
+ RenderSession.checkDeadline();
+ super.renderBlock(context, writer, block);
+ }
+
+ /** The items of one loop, failing the render on the one after the last pass allowed. */
+ private static final class Limited implements Iterator {
+
+ private final Iterator> items;
+ private int passes = 0;
+
+ Limited(Iterator> items) {
+ this.items = items;
+ }
+
+ @Override
+ public boolean hasNext() {
+ return items.hasNext();
+ }
+
+ @Override
+ public Object next() {
+ if (++passes > MAX_PASSES) {
+ throw new RenderLimitException("#foreach made more than "
+ + MAX_PASSES + " passes");
+ }
+ return items.next();
+ }
+ }
+}
diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerResourceLoader.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerResourceLoader.java
index 4159c6437b..89b3ea8c9a 100644
--- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerResourceLoader.java
+++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerResourceLoader.java
@@ -17,10 +17,8 @@
*/
package org.apache.roller.weblogger.ui.rendering.velocity;
-import java.io.ByteArrayInputStream;
-import java.io.InputStreamReader;
import java.io.Reader;
-import java.io.UnsupportedEncodingException;
+import java.io.StringReader;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -30,6 +28,7 @@
import org.apache.roller.weblogger.pojos.TemplateRendition.RenditionType;
import org.apache.roller.weblogger.pojos.WeblogTemplate;
import org.apache.velocity.exception.ResourceNotFoundException;
+import org.apache.velocity.exception.VelocityException;
import org.apache.velocity.runtime.resource.Resource;
import org.apache.velocity.runtime.resource.loader.ResourceLoader;
import org.apache.velocity.util.ExtProperties;
@@ -53,6 +52,11 @@ public void init(ExtProperties configuration) {
if (logger.isDebugEnabled()) {
logger.debug(configuration);
}
+ // see inRenderScope()
+ if (configuration.getBoolean("cache", false)) {
+ throw new VelocityException("resource.loader.roller.cache must be false,"
+ + " so that each weblog renders only its own templates");
+ }
}
/**
@@ -87,7 +91,7 @@ public Reader getResourceReader(String name, String encoding) {
WeblogTemplate page = WebloggerFactory.getWeblogger()
.getWeblogManager().getTemplate(name);
- if (page == null) {
+ if (page == null || !inRenderScope(page)) {
throw new ResourceNotFoundException(
"RollerResourceLoader: page \"" + name + "\" not found");
}
@@ -100,13 +104,8 @@ public Reader getResourceReader(String name, String encoding) {
if (templateCode != null) {
contents = templateCode.getTemplate();
}
- return new InputStreamReader(new ByteArrayInputStream(contents.getBytes(encoding)));
-
- } catch (UnsupportedEncodingException uex) {
- // This should never actually happen. We expect UTF-8 in all JRE
- // installation.
-// logger.error(uex);
- throw new RuntimeException(uex);
+ // the template is already text, so it needs no encoding
+ return new StringReader(contents);
} catch (WebloggerException | ResourceNotFoundException re) {
String msg = "RollerResourceLoader Error: "
@@ -116,6 +115,30 @@ public Reader getResourceReader(String name, String encoding) {
}
}
+ /**
+ * While a template is being rendered, the only stored templates it may
+ * load (by #parse or #include) are those of the weblog being rendered, so
+ * one weblog cannot read or run another's templates by id. Outside
+ * rendering, the template being loaded is the one the servlet chose. This
+ * relies on resource.loader.roller.cache=false in velocity.properties, so
+ * every load comes through here rather than from Velocity's cache; init()
+ * refuses to start with caching on.
+ */
+ private static boolean inRenderScope(WeblogTemplate page) {
+ RenderSession session = RenderSession.current();
+ if (session == null) {
+ return true;
+ }
+ String weblogId = session.getWeblogId();
+ boolean allowed = weblogId != null && page.getWeblog() != null
+ && weblogId.equals(page.getWeblog().getId());
+ if (!allowed) {
+ logger.debug("Refusing template " + page.getId()
+ + " outside the weblog being rendered");
+ }
+ return allowed;
+ }
+
/**
* Files loaded by this resource loader are not reloadable here, as they are
* stored in custom themes and there is no way velocity can trigger a
diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java
new file mode 100644
index 0000000000..7f4abb6073
--- /dev/null
+++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java
@@ -0,0 +1,472 @@
+/*
+ * 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.
+ */
+
+package org.apache.roller.weblogger.ui.rendering.velocity;
+
+import java.util.Locale;
+import java.util.Set;
+import java.util.function.IntPredicate;
+import java.util.function.UnaryOperator;
+import java.util.regex.Matcher;
+
+import org.apache.commons.text.StringEscapeUtils;
+import org.apache.roller.util.RegexUtil;
+import org.apache.roller.weblogger.ui.rendering.model.UtilitiesModel;
+
+/**
+ * Some string methods build a result much longer than their receiver and
+ * arguments, so checking the result's length after the call is too late. This
+ * works out, before a call from a template runs, the longest string it can
+ * build, and names the methods whose result can't be bounded that way. The
+ * same goes for the $utils methods (UtilitiesModel) that escape, encode or
+ * add to text.
+ *
+ * Methods are matched by name so that methods added in later Java versions
+ * (String.indent, String.formatted, StringBuilder.repeat) are covered when
+ * Roller runs on them.
+ */
+final class StringGrowth {
+
+ /**
+ * String methods that are not offered to templates: those that build a
+ * string whose length can't be worked out from the call, and those that
+ * run a regular expression or return a piece for every line, which
+ * DeadlineRegex doesn't run for them.
+ */
+ private static final Set REFUSED_STRING_METHODS = Set.of(
+ "repeat", "format", "formatted", "join", "indent", "splitWithDelimiters", "lines");
+
+ /** String methods whose result is never longer than the receiver or an argument. */
+ private static final Set NON_GROWING_STRING_METHODS = Set.of(
+ "substring", "subSequence", "trim", "strip", "stripLeading",
+ "stripTrailing", "stripIndent", "translateEscapes", "intern",
+ "toString", "copyValueOf");
+
+ /** StringBuilder and StringBuffer methods that are not offered to templates. */
+ private static final Set REFUSED_BUILDER_METHODS = Set.of("repeat");
+
+ /**
+ * UtilitiesModel methods that return a string no longer than an argument,
+ * or a short one of fixed length.
+ */
+ private static final Set NON_GROWING_UTILITIES_METHODS = Set.of(
+ "getModelName", "toString", "formatIso8601Date", "formatIso8601Day",
+ "formatRfc822Date", "format8charsDate", "left", "unescapeHTML",
+ "unescapeXML", "unescapeJavaScript", "removeHTML", "decode");
+
+ /** Characters a number, boolean or other value appended to a builder may take. */
+ private static final long SCALAR_LENGTH = 32;
+
+ /**
+ * The characters toUpperCase or toLowerCase turn into more than one, in
+ * any locale. The Lithuanian lower case of I, J and I with ogonek gains a
+ * dot before an accent, so those count as growing by one.
+ */
+ private static final Growth CASE_GROWTH = new Growth(c -> {
+ String s = String.valueOf((char) c);
+ int longest = 1;
+ for (Locale l : new Locale[] {Locale.ROOT, Locale.forLanguageTag("tr"),
+ Locale.forLanguageTag("az"), Locale.forLanguageTag("lt")}) {
+ longest = Math.max(longest, Math.max(s.toUpperCase(l).length(),
+ s.toLowerCase(l).length()));
+ }
+ return c == 'I' || c == 'J' || c == '\u012e' ? Math.max(longest, 2) : longest;
+ });
+
+ /** Most characters addNofollow is taken to make of one character; see forUtilities. */
+ private static final long NOFOLLOW_GROWTH = 9;
+
+ /** Most characters a pattern letter of a date format writes, with room to spare. */
+ private static final long DATE_LETTER_LENGTH = 64;
+
+ /** What UtilitiesModel.escapeHTML and escapeXML make of each character. */
+ private static final Growth HTML_ESCAPED = escaped(StringEscapeUtils::escapeHtml4);
+ private static final Growth XML_ESCAPED = escaped(StringEscapeUtils::escapeXml11);
+
+ private StringGrowth() {
+ }
+
+ /**
+ * @return true if the method must not be offered on this receiver: it can
+ * build a string whose length can't be worked out from the call
+ */
+ static boolean isRefused(Object receiver, String methodName, Class> returnType) {
+ if (receiver instanceof Class) {
+ // Velocity calls a class's static methods on its Class object,
+ // which would offer String.format and join by another name.
+ // SecureUberspector allows only getName of Class's own methods.
+ return !"getName".equals(methodName);
+ }
+ if (receiver instanceof String) {
+ if (REFUSED_STRING_METHODS.contains(methodName)) {
+ return true;
+ }
+ // a method this class doesn't know about that returns a string
+ return returnType != null && CharSequence.class.isAssignableFrom(returnType)
+ && !NON_GROWING_STRING_METHODS.contains(methodName)
+ && !isBoundedStringMethod(methodName);
+ }
+ if (receiver instanceof StringBuilder || receiver instanceof StringBuffer) {
+ return REFUSED_BUILDER_METHODS.contains(methodName);
+ }
+ if (receiver instanceof UtilitiesModel) {
+ // a method added later is refused until it is bounded here
+ return returnType != null && CharSequence.class.isAssignableFrom(returnType)
+ && !NON_GROWING_UTILITIES_METHODS.contains(methodName)
+ && !isBoundedUtilitiesMethod(methodName);
+ }
+ return false;
+ }
+
+ private static boolean isBoundedStringMethod(String methodName) {
+ switch (methodName) {
+ case "replace":
+ case "replaceAll":
+ case "replaceFirst":
+ case "concat":
+ case "toUpperCase":
+ case "toLowerCase":
+ case "valueOf":
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ private static boolean isBoundedUtilitiesMethod(String methodName) {
+ switch (methodName) {
+ case "replace":
+ case "toUpperCase":
+ case "escapeHTML":
+ case "transformToHTMLSubset":
+ case "escapeXML":
+ case "escapeJavaScript":
+ case "encode":
+ case "hexEncode":
+ case "autoformat":
+ case "addNofollow":
+ case "encodeEmail":
+ case "truncate":
+ case "truncateNicely":
+ case "truncateText":
+ case "toBase64":
+ case "formatDate":
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ /**
+ * @return the most characters the call can put in one string, or 0 when
+ * it doesn't build a string longer than its receiver or arguments
+ */
+ static long maxResultLength(Object receiver, String methodName, Object[] args) {
+ Object[] a = args == null ? new Object[0] : args;
+ if (receiver instanceof String) {
+ return forString((String) receiver, methodName, a);
+ }
+ if (receiver instanceof StringBuilder || receiver instanceof StringBuffer) {
+ return forBuilder((CharSequence) receiver, methodName, a);
+ }
+ if (receiver instanceof UtilitiesModel) {
+ return forUtilities(methodName, a);
+ }
+ return 0;
+ }
+
+ private static long forUtilities(String methodName, Object[] a) {
+ // the arguments already have the method's parameter types: Velocity
+ // finds no method for a call whose arguments don't fit
+ CharSequence s = a.length > 0 ? text(a[0]) : null;
+ switch (methodName) {
+ case "replace": {
+ if (a.length < 3 || s == null) {
+ return 0;
+ }
+ long maxCount = a.length > 3 && a[3] instanceof Number
+ ? ((Number) a[3]).longValue() : -1;
+ CharSequence target = text(a[1]);
+ if (target == null || target.length() == 0) {
+ // StringUtils.replace leaves the text alone for an empty target
+ return 0;
+ }
+ return literalReplace(s.toString(), target.toString(), length(a[2]), maxCount);
+ }
+ case "toUpperCase":
+ return caseChange(s);
+ case "escapeHTML":
+ case "transformToHTMLSubset":
+ // transformToHTMLSubset only shrinks text apart from the link
+ // addresses it escapes the same way
+ return HTML_ESCAPED.length(s);
+ case "escapeXML":
+ return XML_ESCAPED.length(s);
+ case "escapeJavaScript":
+ // at most six characters (\u00e9)
+ return grown(s, 6, c -> c < 0x20 || c > 0x7e || c == '\'' || c == '"'
+ || c == '\\' || c == '/');
+ case "encode":
+ // up to three UTF-8 bytes of %XX each; a space becomes '+'
+ return grown(s, 9, c -> !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'
+ || c >= '0' && c <= '9' || c == '.' || c == '-' || c == '*'
+ || c == '_' || c == ' '));
+ case "hexEncode":
+ // every UTF-8 byte becomes %XX
+ return add(multiply(3, s == null ? 0 : s.length()),
+ multiply(6, count(s, c -> c >= 0x80)));
+ case "autoformat":
+ return grown(s, " ".length(), c -> c == '\n');
+ case "addNofollow":
+ // each link (each " 3 ? a[3] : null));
+ case "toBase64":
+ return a.length > 0 && a[0] instanceof byte[]
+ ? multiply(4, (((byte[]) a[0]).length + 2) / 3) : 0;
+ case "formatDate": {
+ CharSequence fmt = a.length > 1 ? text(a[1]) : null;
+ return grown(fmt, DATE_LETTER_LENGTH,
+ c -> c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z');
+ }
+ default:
+ return 0;
+ }
+ }
+
+ /**
+ * RegexUtil.encodeEmail hex encodes each mailto address, tripling it, and
+ * then turns the '@' and a '.' of each address into -AT- and -DOT-.
+ */
+ private static long encodedEmail(CharSequence s) {
+ if (s == null) {
+ return 0;
+ }
+ long mailtoChars = 0;
+ Matcher m = RegexUtil.MAILTO_PATTERN.matcher(s);
+ while (m.find()) {
+ mailtoChars += m.end(1) - m.start(1);
+ }
+ long perAt = "-AT-".length() - 1 + "-DOT-".length() - 1;
+ return add(add(s.length(), multiply(2, mailtoChars)),
+ multiply(perAt, count(s, c -> c == '@')));
+ }
+
+ /**
+ * How many characters each char becomes, found by trying each one, so
+ * that only the characters that really grow are counted.
+ */
+ private static final class Growth {
+
+ private final byte[] extra = new byte[Character.MAX_VALUE + 1];
+
+ Growth(java.util.function.IntUnaryOperator lengthOf) {
+ for (int c = 0; c <= Character.MAX_VALUE; c++) {
+ extra[c] = (byte) Math.max(0, lengthOf.applyAsInt(c) - 1);
+ }
+ }
+
+ long length(CharSequence s) {
+ if (s == null) {
+ return 0;
+ }
+ long n = s.length();
+ for (int i = 0; i < s.length(); i++) {
+ n += extra[s.charAt(i)];
+ }
+ return n;
+ }
+ }
+
+ private static Growth escaped(UnaryOperator escape) {
+ return new Growth(c -> escape.apply(String.valueOf((char) c)).length());
+ }
+
+ /** Length of a case change of s. */
+ private static long caseChange(CharSequence s) {
+ return CASE_GROWTH.length(s);
+ }
+
+ /** Length of s when each character that matches can become up to perChar characters. */
+ private static long grown(CharSequence s, long perChar, IntPredicate grows) {
+ return s == null ? 0 : add(s.length(), multiply(perChar - 1, count(s, grows)));
+ }
+
+ private static long count(CharSequence s, IntPredicate matches) {
+ long n = 0;
+ for (int i = 0; s != null && i < s.length(); i++) {
+ if (matches.test(s.charAt(i))) {
+ n++;
+ }
+ }
+ return n;
+ }
+
+ private static long occurrencesIgnoringCase(String s, String target) {
+ long n = 0;
+ for (int i = 0; i + target.length() <= s.length(); i++) {
+ if (s.regionMatches(true, i, target, 0, target.length())) {
+ n++;
+ i += target.length() - 1;
+ }
+ }
+ return n;
+ }
+
+ private static CharSequence text(Object value) {
+ if (value == null || value instanceof CharSequence) {
+ return (CharSequence) value;
+ }
+ return value instanceof char[] ? new String((char[]) value) : String.valueOf(value);
+ }
+
+ private static long forString(String s, String methodName, Object[] a) {
+ long len = s.length();
+ switch (methodName) {
+ case "replace":
+ if (a.length == 2 && a[0] instanceof CharSequence) {
+ return literalReplace(s, a[0].toString(), length(a[1]), -1);
+ }
+ return len;
+ case "replaceAll":
+ case "replaceFirst":
+ // DeadlineRegex runs these and checks the limit as it goes
+ return 0;
+ case "concat":
+ return add(len, length(a.length > 0 ? a[0] : null));
+ case "valueOf":
+ // a list or map passed as an Object is printed in full
+ return a.length == 1 ? length(a[0]) : 0;
+ case "toUpperCase":
+ case "toLowerCase":
+ return caseChange(s);
+ default:
+ return 0;
+ }
+ }
+
+ private static long forBuilder(CharSequence b, String methodName, Object[] a) {
+ long len = b.length();
+ switch (methodName) {
+ case "setLength":
+ case "ensureCapacity":
+ return a.length == 1 && a[0] instanceof Number
+ ? ((Number) a[0]).longValue() : 0;
+ case "append":
+ case "appendCodePoint":
+ case "insert":
+ case "replace": {
+ long total = len;
+ for (Object arg : a) {
+ // a list or map appended as an Object is printed in full
+ total = add(total, arg == null ? "null".length() : length(arg));
+ }
+ return total;
+ }
+ default:
+ return 0;
+ }
+ }
+
+ /** Length of s with up to maxCount (or all, when negative) target occurrences replaced. */
+ private static long literalReplace(String s, String target, long replacementLength,
+ long maxCount) {
+ long occurrences;
+ if (target.isEmpty()) {
+ occurrences = s.length() + 1L;
+ } else {
+ occurrences = 0;
+ for (int i = s.indexOf(target); i >= 0; i = s.indexOf(target, i + target.length())) {
+ occurrences++;
+ if (occurrences == maxCount) {
+ break;
+ }
+ }
+ }
+ if (maxCount >= 0) {
+ occurrences = Math.min(occurrences, maxCount);
+ }
+ long growth = Math.max(0, replacementLength - target.length());
+ return add(s.length(), multiply(occurrences, growth));
+ }
+
+ private static long length(Object value) {
+ if (value instanceof CharSequence) {
+ return ((CharSequence) value).length();
+ }
+ if (value instanceof char[]) {
+ return ((char[]) value).length;
+ }
+ if (ValueLimits.holdsValues(value)) {
+ RenderSession session = RenderSession.current();
+ return ValueLimits.textLength(value,
+ session == null ? Long.MAX_VALUE : session.getMaxOutputChars());
+ }
+ return value == null ? 0 : SCALAR_LENGTH;
+ }
+
+ /**
+ * Throws if $utils.split would return more pieces than a template loop
+ * can visit. It splits at any of the separator characters (whitespace
+ * when there are none) and drops empty pieces, so the pieces are the
+ * runs of other characters.
+ */
+ static void checkPieces(Object receiver, String methodName, Object[] args) {
+ if (!(receiver instanceof UtilitiesModel) || !"split".equals(methodName)
+ || args == null || args.length != 2 || !(args[0] instanceof CharSequence)) {
+ return;
+ }
+ CharSequence s = (CharSequence) args[0];
+ String separators = args[1] == null ? null : args[1].toString();
+ long pieces = 0;
+ boolean inPiece = false;
+ for (int i = 0; i < s.length(); i++) {
+ char c = s.charAt(i);
+ boolean separator = separators == null ? Character.isWhitespace(c)
+ : separators.indexOf(c) >= 0;
+ if (!separator && !inPiece) {
+ pieces++;
+ }
+ inPiece = !separator;
+ }
+ if (pieces > DeadlineRegex.MAX_SPLIT_PIECES) {
+ throw new RenderLimitException("split produced more than "
+ + DeadlineRegex.MAX_SPLIT_PIECES + " pieces");
+ }
+ }
+
+ private static long add(long a, long b) {
+ long sum = a + b;
+ return sum < 0 ? Long.MAX_VALUE : sum;
+ }
+
+ private static long multiply(long a, long b) {
+ if (a == 0 || b == 0) {
+ return 0;
+ }
+ return a > Long.MAX_VALUE / b ? Long.MAX_VALUE : a * b;
+ }
+}
diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/ValueLimits.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/ValueLimits.java
new file mode 100644
index 0000000000..a682dee3c9
--- /dev/null
+++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/ValueLimits.java
@@ -0,0 +1,279 @@
+/*
+ * 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.
+ */
+
+
+package org.apache.roller.weblogger.ui.rendering.velocity;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.ArrayDeque;
+import java.util.Collection;
+import java.util.Deque;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Bounds for the values other than strings that a template works with: the
+ * text of a list or map, the lists and maps it grows, and the big numbers
+ * Velocity makes when arithmetic overflows a long. One call on these can take
+ * more memory or time than a whole page, and a call can't be stopped once it
+ * has started, so each is checked before it runs.
+ */
+final class ValueLimits {
+
+ /** Most bits of a number a template may make. */
+ static final long MAX_NUMBER_BITS = 100_000;
+
+ /** Most element comparisons one containsAll, removeAll or retainAll may make. */
+ static final long MAX_COMPARISONS = 10_000_000;
+
+ private ValueLimits() {
+ }
+
+ /** A list or map being walked by textLength. */
+ private static final class Frame {
+ final Object container;
+ final Iterator> items;
+ boolean first = true;
+
+ Frame(Object container) {
+ this.container = container;
+ this.items = container instanceof Map
+ ? ((Map, ?>) container).entrySet().iterator()
+ : ((Collection>) container).iterator();
+ }
+ }
+
+ /**
+ * @return the length of String.valueOf(value), or a number above limit
+ * once it is known to be longer. A list or map is walked element
+ * by element instead of being turned into text, and the walk
+ * stops at the limit, so a huge or deeply nested one is cheap to
+ * check.
+ */
+ static long textLength(Object value, long limit) {
+ if (value instanceof Map.Entry) {
+ Map.Entry, ?> entry = (Map.Entry, ?>) value;
+ long key = textLength(entry.getKey(), limit);
+ return key > limit ? key : 1 + key + textLength(entry.getValue(), limit - key);
+ }
+ if (!isContainer(value)) {
+ return leafLength(value);
+ }
+ Deque walks = new ArrayDeque<>();
+ walks.push(new Frame(value));
+ // "[]" or "{}"
+ long length = 2;
+ while (!walks.isEmpty() && length <= limit) {
+ Frame walk = walks.peek();
+ if (!walk.items.hasNext()) {
+ walks.pop();
+ continue;
+ }
+ if (!walk.first) {
+ // ", "
+ length += 2;
+ }
+ walk.first = false;
+ Object item = walk.items.next();
+ if (walk.container instanceof Map) {
+ Map.Entry, ?> entry = (Map.Entry, ?>) item;
+ // key=value
+ length += 1 + visit(entry.getKey(), walk, walks)
+ + visit(entry.getValue(), walk, walks);
+ } else {
+ length += visit(item, walk, walks);
+ }
+ }
+ return length;
+ }
+
+ /** @return the length of item, or 2 for the brackets of a container it starts walking */
+ private static long visit(Object item, Frame walk, Deque walks) {
+ if (item == walk.container) {
+ // how AbstractCollection and AbstractMap print themselves
+ return item instanceof Map ? "(this Map)".length() : "(this Collection)".length();
+ }
+ if (isContainer(item)) {
+ walks.push(new Frame(item));
+ return 2;
+ }
+ if (item instanceof Map.Entry) {
+ // key=value, as a map's entries print
+ Map.Entry, ?> entry = (Map.Entry, ?>) item;
+ return 1 + visit(entry.getKey(), walk, walks) + visit(entry.getValue(), walk, walks);
+ }
+ return leafLength(item);
+ }
+
+ private static boolean isContainer(Object value) {
+ return value instanceof Collection || value instanceof Map;
+ }
+
+ /** @return true if the value's text is built from a list or map it holds */
+ static boolean holdsValues(Object value) {
+ return isContainer(value) || value instanceof Map.Entry;
+ }
+
+ private static long leafLength(Object value) {
+ return value instanceof CharSequence ? ((CharSequence) value).length()
+ : String.valueOf(value).length();
+ }
+
+ /** @return the number of elements of a list or map, or 0 for anything else */
+ static long size(Object value) {
+ if (value instanceof Collection) {
+ return ((Collection>) value).size();
+ }
+ return value instanceof Map ? ((Map, ?>) value).size() : 0;
+ }
+
+ /**
+ * Checks a call on a list or map before it runs: the items addAll or
+ * putAll may add, or toArray or clone may copy, have to fit the render's
+ * budget, a comparison of every element with every other has to stay
+ * small, and the text of toString has to fit the output limit.
+ */
+ static void checkContainerCall(Object receiver, String methodName, Object[] args,
+ long maxChars) {
+ long receiverSize = size(receiver);
+ boolean adds = "addAll".equals(methodName) || "putAll".equals(methodName);
+ long added = 0;
+ for (Object arg : args) {
+ long argSize = size(arg);
+ if (adds) {
+ added += argSize;
+ }
+ boolean compares = "containsAll".equals(methodName) && !(receiver instanceof Set)
+ || ("removeAll".equals(methodName) || "retainAll".equals(methodName))
+ && !(arg instanceof Set);
+ if (compares && receiverSize > 0 && argSize > MAX_COMPARISONS / receiverSize) {
+ throw new RenderLimitException(methodName + " would compare more than "
+ + MAX_COMPARISONS + " pairs of elements");
+ }
+ }
+ if (isCopy(methodName)) {
+ added += receiverSize;
+ }
+ RenderSession.checkItems(added);
+ if ("toString".equals(methodName) && args.length == 0) {
+ RenderSession.checkLength(textLength(receiver, maxChars));
+ }
+ }
+
+ /** @return true for the calls that return a copy of a list or map's items */
+ static boolean isCopy(String methodName) {
+ return "toArray".equals(methodName) || "clone".equals(methodName);
+ }
+
+ /**
+ * Checks a call on a big number before it runs, for the calls whose
+ * result can be far larger than the number: pow, the shifts and the bit
+ * setters. Primality tests are refused, as they can take minutes on a
+ * number that fits the limit.
+ */
+ static void checkNumberCall(Object receiver, String methodName, Object[] args) {
+ if (receiver instanceof BigInteger) {
+ BigInteger n = (BigInteger) receiver;
+ long arg = args.length == 1 && args[0] instanceof Number
+ ? ((Number) args[0]).longValue() : 0;
+ long bits;
+ switch (methodName) {
+ case "pow":
+ bits = multiply(n.bitLength(), Math.max(arg, 0));
+ break;
+ case "shiftLeft":
+ bits = n.bitLength() + Math.max(arg, 0);
+ break;
+ case "shiftRight":
+ bits = n.bitLength() - Math.min(arg, 0);
+ break;
+ case "setBit":
+ case "flipBit":
+ bits = Math.max(n.bitLength(), arg + 1);
+ break;
+ case "isProbablePrime":
+ case "nextProbablePrime":
+ throw new RenderLimitException(methodName + " is not available to templates");
+ default:
+ bits = 0;
+ }
+ checkBits(bits);
+ } else if (receiver instanceof BigDecimal) {
+ BigDecimal d = (BigDecimal) receiver;
+ long arg = args.length > 0 && args[0] instanceof Number
+ ? Math.abs(((Number) args[0]).longValue()) : 0;
+ // a scale far from zero is cheap to hold, but these write it out
+ // in full, at a little over three bits a digit
+ long scale = Math.abs((long) d.scale());
+ switch (methodName) {
+ case "pow":
+ checkBits(multiply(bits(d), arg));
+ break;
+ case "toPlainString":
+ case "toBigInteger":
+ case "toBigIntegerExact":
+ checkBits(bits(d) + 4 * scale);
+ break;
+ case "setScale":
+ case "movePointLeft":
+ case "movePointRight":
+ case "scaleByPowerOfTen":
+ checkBits(bits(d) + 4 * (scale + arg));
+ break;
+ default:
+ break;
+ }
+ }
+ }
+
+ /** Throws if a number a template made is larger than MAX_NUMBER_BITS. */
+ static void checkResult(Object result) {
+ if (result instanceof BigInteger || result instanceof BigDecimal) {
+ checkBits(bits((Number) result));
+ }
+ }
+
+ /** @return about how many bits a number holds */
+ static long bits(Number n) {
+ if (n instanceof BigInteger) {
+ return ((BigInteger) n).bitLength();
+ }
+ if (n instanceof BigDecimal) {
+ // a little over three bits a digit
+ return ((BigDecimal) n).precision() * 4L;
+ }
+ return Long.SIZE;
+ }
+
+ static void checkBits(long bits) {
+ if (bits > MAX_NUMBER_BITS) {
+ throw new RenderLimitException("a number would have more than "
+ + MAX_NUMBER_BITS + " bits");
+ }
+ }
+
+ private static long multiply(long a, long b) {
+ if (a == 0 || b == 0) {
+ return 0;
+ }
+ return a > Long.MAX_VALUE / b ? Long.MAX_VALUE : a * b;
+ }
+}
diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/VelocityRenderer.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/VelocityRenderer.java
index 3ea45bab61..744bdc53c2 100644
--- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/VelocityRenderer.java
+++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/VelocityRenderer.java
@@ -21,14 +21,21 @@
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
+import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.roller.util.RollerConstants;
import org.apache.roller.weblogger.pojos.Template;
+import org.apache.roller.weblogger.pojos.Weblog;
+import org.apache.roller.weblogger.pojos.WeblogTemplate;
+import org.apache.roller.weblogger.pojos.wrapper.WeblogWrapper;
import org.apache.roller.weblogger.ui.rendering.Renderer;
import org.apache.roller.weblogger.ui.rendering.RenderingException;
import org.apache.roller.weblogger.ui.rendering.mobile.MobileDeviceRepository;
+import org.apache.roller.weblogger.ui.rendering.model.FeedModel;
+import org.apache.roller.weblogger.ui.rendering.model.PageModel;
+import org.apache.roller.weblogger.ui.rendering.model.SearchResultsFeedModel;
import org.apache.roller.weblogger.ui.rendering.model.UtilitiesModel;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.context.Context;
@@ -42,6 +49,10 @@ public class VelocityRenderer implements Renderer {
private static final Log log = LogFactory.getLog(VelocityRenderer.class);
+ // ids Roller gives stored templates
+ private static final Pattern STORED_TEMPLATE_ID = Pattern.compile(
+ "\\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\\b");
+
// the original template we are supposed to render
private final Template renderTemplate;
private final MobileDeviceRepository.DeviceType deviceType;
@@ -79,6 +90,8 @@ public VelocityRenderer(Template template,
// in the case of a velocity error we want to render an
// error page instead so the user knows what was wrong
velocityException = ex;
+ log.warn("Error loading [" + template.getId() + "]: "
+ + forLog(ex.getMessage()));
// need to lookup error page template
velocityTemplate = RollerVelocity.getTemplate("error-page.vm", deviceType);
@@ -102,16 +115,19 @@ public VelocityRenderer(Template template,
public void render(Map model, Writer out)
throws RenderingException {
- try {
+ if (velocityException != null) {
- if (velocityException != null) {
+ // Render exception
+ renderException(model, out, null);
- // Render exception
- renderException(model, out, null);
+ // and we're done
+ return;
+ }
- // and we're done
- return;
- }
+ // the session bounds output and time, and scopes stored templates
+ // loaded by #parse and #include to the weblog being rendered
+ RenderSession session = RenderSession.begin(weblogIdFor(model));
+ try {
long startTime = System.currentTimeMillis();
@@ -127,7 +143,7 @@ public void render(Map model, Writer out)
// render base template to a temporary StringWriter
StringWriter sw = new StringWriter();
- velocityTemplate.merge(ctx, sw);
+ velocityTemplate.merge(ctx, new RenderLimitWriter(sw, session));
// put rendered template into context
ctx.put("decorator_body", sw.toString());
@@ -135,12 +151,12 @@ public void render(Map model, Writer out)
log.debug("Applying decorator " + velocityDecorator.getName());
// now render decorator to our output writer
- velocityDecorator.merge(ctx, out);
+ velocityDecorator.merge(ctx, new RenderLimitWriter(out, session));
} else {
// no decorator, so just merge template to our output writer
- velocityTemplate.merge(ctx, out);
+ velocityTemplate.merge(ctx, new RenderLimitWriter(out, session));
}
long endTime = System.currentTimeMillis();
@@ -148,20 +164,99 @@ public void render(Map model, Writer out)
log.debug("Rendered [" + renderTemplate.getId() + "] in "
+ renderTime + " secs");
+ return;
- } catch (VelocityException ex) {
+ } catch (Exception ex) {
+ RenderLimitException limit = findLimit(ex);
+ if (limit != null) {
+ // the partial output is discarded by the caller, which
+ // fails the request as for any other rendering error
+ log.error("Stopped rendering [" + renderTemplate.getId()
+ + "]: " + limit.getMessage());
+ throw new RenderingException("Error during rendering", limit);
+ }
+ if (!(ex instanceof VelocityException)) {
+ // wrap and rethrow so caller can deal with it
+ throw new RenderingException("Error during rendering", ex);
+ }
// in the case of a velocity error including a page we want to
// render an error page instead so the user knows what was wrong
velocityException = ex;
+ log.warn("Error rendering [" + renderTemplate.getId() + "]: "
+ + forLog(ex.getMessage()));
- // need to lookup parse error template
- renderException(model, out, "error-parse.vm");
+ } finally {
+ session.end();
+ }
- } catch (Exception ex) {
- // wrap and rethrow so caller can deal with it
- throw new RenderingException("Error during rendering", ex);
+ // need to lookup parse error template
+ renderException(model, out, "error-parse.vm");
+ }
+
+ /**
+ * @return the id of the weblog being rendered, from the template when it
+ * is one of the weblog's own, otherwise from the page model; null
+ * when the render is not for a weblog
+ */
+ private String weblogIdFor(Map model) {
+ if (renderTemplate instanceof WeblogTemplate) {
+ Weblog weblog = ((WeblogTemplate) renderTemplate).getWeblog();
+ return weblog == null ? null : weblog.getId();
+ }
+ Object pageModel = model == null ? null : model.get("model");
+ WeblogWrapper weblog = null;
+ if (pageModel instanceof PageModel) {
+ weblog = ((PageModel) pageModel).getWeblog();
+ } else if (pageModel instanceof FeedModel) {
+ weblog = ((FeedModel) pageModel).getWeblog();
+ } else if (pageModel instanceof SearchResultsFeedModel) {
+ weblog = ((SearchResultsFeedModel) pageModel).getWeblog();
+ }
+ return weblog == null ? null : weblog.getId();
+ }
+
+ /**
+ * @return the exception's message as the public error page shows it, with
+ * template ids replaced by the template's name, or by "template"
+ * for other stored templates; the ids stay in the log
+ */
+ private String publicMessage(Exception ex) {
+ String message = brief(ex.getMessage());
+ if (message == null) {
+ return null;
+ }
+ if (renderTemplate.getId() != null && renderTemplate.getName() != null) {
+ message = message.replace(renderTemplate.getId(), renderTemplate.getName());
+ }
+ return STORED_TEMPLATE_ID.matcher(message).replaceAll("template");
+ }
+
+ /** Most characters of a template error's message that are logged or shown. */
+ private static final int MAX_MESSAGE_CHARS = 1000;
+
+ /**
+ * @return the start of a message, which can quote a value from the
+ * template of any length
+ */
+ private static String brief(String message) {
+ return message == null || message.length() <= MAX_MESSAGE_CHARS ? message
+ : message.substring(0, MAX_MESSAGE_CHARS) + "...";
+ }
+
+ /** @return the start of a message, on one line */
+ private static String forLog(String message) {
+ String m = brief(message);
+ return m == null ? null : m.replace('\r', ' ').replace('\n', ' ');
+ }
+
+ private static RenderLimitException findLimit(Throwable t) {
+ for (int depth = 0; t != null && depth < 20; depth++, t = t.getCause()) {
+ if (t instanceof RenderLimitException) {
+ return (RenderLimitException) t;
+ }
}
+ return null;
}
/**
@@ -190,7 +285,7 @@ private void renderException(Map model, Writer out,
Context ctx = new VelocityContext(model);
ctx.put("exception", velocityException);
- ctx.put("exceptionSource", renderTemplate.getId());
+ ctx.put("exceptionMessage", publicMessage(velocityException));
ctx.put("exceptionDevice", deviceType);
ctx.put("utils", new UtilitiesModel());
diff --git a/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties b/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties
index 91979b2b2b..141b21448d 100644
--- a/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties
+++ b/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties
@@ -494,6 +494,15 @@ org.apache.roller.weblogger.ui.rendering.model.PlanetModel
# Velocity settings
velocity.properties=/WEB-INF/velocity.properties
+# Limits on rendering one weblog page or feed. A template that writes more
+# characters (or builds a longer string) than maxOutputChars, or takes longer
+# than maxRenderSeconds, fails with an error in the log, as does a #foreach of
+# more than 100,000 passes. While maxOutputChars is set, a render may also
+# build at most ten times that many characters of strings in memory, and add
+# at most 1,000,000 items to lists and maps. Zero means no limit.
+rendering.maxOutputChars=10485760
+rendering.maxRenderSeconds=30
+
#-----------------------------------------------------------------------------
# Weblog ping system
#-----------------------------------------------------------------------------
diff --git a/app/src/main/webapp/WEB-INF/velocity.properties b/app/src/main/webapp/WEB-INF/velocity.properties
index 190a7bbbca..ef015936e6 100644
--- a/app/src/main/webapp/WEB-INF/velocity.properties
+++ b/app/src/main/webapp/WEB-INF/velocity.properties
@@ -62,14 +62,45 @@ velocimacro.library.autoreload=false
# Allow Velocimacros to be defined in regular templates
velocimacro.inline.allow=true
-# Allow template authors to define macros in any template
-velocimacro.inline.local_scope=false
+# Macros a template defines belong to that template, and to the render it
+# starts, so one weblog's macro never replaces another's of the same name and
+# an edited macro takes effect on the next render. With replace_global, the
+# page's macros are also seen by the templates it #parses, and a macro
+# defined in a #parse'd template is seen by the rest of the page, as before.
+# Library macros (velocimacro.library.path) stay global.
+velocimacro.inline.local_scope=true
+velocimacro.inline.replace_global=true
# set encoding/charset to UTF-8
resource.default_encoding=UTF-8
default.contentType=text/html; charset=utf-8
-introspector.uberspect.class=org.apache.velocity.util.introspection.SecureUberspector
+# Weblog templates are written by weblog authors, so a render is bounded by
+# rendering.maxOutputChars and rendering.maxRenderSeconds in
+# roller.properties, and by a budget for the strings and list items it builds
+# in memory (RenderSession). Each setting below does part of that:
+# - parser.class: RenderLimitParser swaps in nodes that stop string literals,
+# + and blocks used as strings at the output limit as they are built, check
+# the text of a list or map before == or != compares it with a string, and
+# check the size of big numbers before * multiplies them.
+# - introspector.uberspect.class: RenderLimitUberspector, chained after
+# SecureUberspector, checks the deadline on every method call and property
+# read, stops a call that returns or could build a string longer than the
+# output limit, a list or map past the budget, or a number too large to
+# work with, and runs regular expressions given to String methods under
+# the deadline. It does not offer the methods whose result can't be bounded
+# from the call: repeat, format, formatted, join, indent, lines and
+# splitWithDelimiters on String, any other String method returning a string
+# that StringGrowth doesn't know, repeat on StringBuilder and StringBuffer,
+# and the methods of a Class object other than getName.
+# - runtime.custom_directives: RollerForeach checks the deadline on every
+# #foreach pass, and fails the render on a loop of more than 100,000 passes.
+# - event_handler.reference_insertion.class: RenderLimitInsertionHandler
+# checks the deadline, and each inserted value against the output limit.
+parser.class=org.apache.roller.weblogger.ui.rendering.velocity.RenderLimitParser
+introspector.uberspect.class=org.apache.velocity.util.introspection.SecureUberspector,org.apache.roller.weblogger.ui.rendering.velocity.RenderLimitUberspector
+runtime.custom_directives=org.apache.roller.weblogger.ui.rendering.velocity.RollerForeach
+event_handler.reference_insertion.class=org.apache.roller.weblogger.ui.rendering.velocity.RenderLimitInsertionHandler
# SecureUberspector governs method access, not resource resolution, so the
# include directives are confined separately.
diff --git a/app/src/main/webapp/WEB-INF/velocity/templates/error-page.vm b/app/src/main/webapp/WEB-INF/velocity/templates/error-page.vm
index 94b84fee99..194bddbadc 100644
--- a/app/src/main/webapp/WEB-INF/velocity/templates/error-page.vm
+++ b/app/src/main/webapp/WEB-INF/velocity/templates/error-page.vm
@@ -69,11 +69,7 @@
Message
- $utils.autoformat($utils.escapeHTML($exception.getMessage()))
-
-
- Type
- $exceptionSource
+ $utils.autoformat($utils.escapeHTML($exceptionMessage))
Exception
diff --git a/app/src/main/webapp/WEB-INF/velocity/templates/error-parse.vm b/app/src/main/webapp/WEB-INF/velocity/templates/error-parse.vm
index bdb378e8a9..fa466cc5a4 100644
--- a/app/src/main/webapp/WEB-INF/velocity/templates/error-parse.vm
+++ b/app/src/main/webapp/WEB-INF/velocity/templates/error-parse.vm
@@ -34,11 +34,7 @@
Message
- $utils.autoformat($utils.escapeHTML($exception.getMessage()))
-
-
- Type
- $exceptionSource
+ $utils.autoformat($utils.escapeHTML($exceptionMessage))
Exception
diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegexTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegexTest.java
new file mode 100644
index 0000000000..865d17582f
--- /dev/null
+++ b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegexTest.java
@@ -0,0 +1,189 @@
+/*
+ * 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.
+ */
+
+package org.apache.roller.weblogger.ui.rendering.velocity;
+
+import java.lang.management.ManagementFactory;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** DeadlineRegex has to give the same results as the String methods it stands in for. */
+class DeadlineRegexTest {
+
+ private static final String[] TEXTS = {"", "a", "a,b,,c,,", "Hello, World", " x y "};
+ private static final String[] PATTERNS = {"", ",", "\\s+", "l+", "(?=(.*))", "(.)", "\\b", "$"};
+ private static final String[] REPLACEMENTS = {"", "x", "$0", "[$1]", "\\$"};
+
+ /**
+ * Expressions in which part can match an empty string in more than one
+ * way at the same place are refused; the rest, including ones with
+ * optional parts, lookarounds and alternatives, still run.
+ */
+ @Test
+ void refusesExpressionsThatRepeatAnEmptyMatch() {
+ String[] refused = {
+ "(?:a?|b?)c", "(|)z", "(?:)*", "x(?:(?:)?){3}", "\\b*", "(?=)+", "^?a",
+ "()\\1*", "(?:(?:a|){2})", "(?a*|b*)", "(?i:x?|y?)", "((a)|(b)?|c*)d",
+ "(?:(?<=k)|(? DeadlineRegex.checkPattern(regex),
+ regex);
+ }
+ String[] allowed = {
+ "", "a", "(\\d+)-(\\d+)", "(?i)foo|bar", "(ab)+", "^\\s+|\\s+$",
+ "(https?://)?(www\\.)?", "foo(?=\\s|$)", "[()|?*]+", "\\Q(|)*\\E",
+ "(?\\d{4})-(\\d{2})", "a|", "(a|b|)c", "(?:\\.\\d+)?", "(\\w)\\1",
+ "(.*a){12}b", "[^\\]()]*",
+ };
+ for (String regex : allowed) {
+ DeadlineRegex.checkPattern(regex);
+ }
+ for (String p : PATTERNS) {
+ DeadlineRegex.checkPattern(p);
+ }
+ }
+
+ /** As String does: replaceFirst refuses null, and replaceAll does once it matches. */
+ @Test
+ void aNullReplacementIsRefusedAsByString() {
+ assertThrows(NullPointerException.class,
+ () -> DeadlineRegex.invoke("abc", "replaceAll", new Object[] {"b", null}));
+ assertThrows(NullPointerException.class,
+ () -> DeadlineRegex.invoke("abc", "replaceFirst", new Object[] {"x", null}));
+ assertEquals("abc", DeadlineRegex.invoke("abc", "replaceAll", new Object[] {"x", null}));
+ }
+
+ /**
+ * A replacement is counted by the groups it refers to, so moving text
+ * around in a string near the limit still works.
+ */
+ @Test
+ void replacementsCountOnlyTheGroupsTheyUse() {
+ RenderSession session = RenderSession.begin(null);
+ try {
+ int length = (int) (session.getMaxOutputChars() * 3 / 5);
+ String s = "abc" + "0".repeat(length - 3);
+ String swapped = (String) DeadlineRegex.invoke(s, "replaceAll",
+ new Object[] {"(?s)^(.)(.)(.)(.*)$", "$3$2$1$4"});
+ assertEquals(length, swapped.length());
+ assertEquals("cba0", swapped.substring(0, 4));
+ assertEquals("", DeadlineRegex.invoke("b", "replaceAll",
+ new Object[] {"(?b)", "<${x}>"}));
+ assertEquals("b1", DeadlineRegex.invoke("b", "replaceAll",
+ new Object[] {"(b)", "$11"}));
+ // a group used twice is counted twice
+ assertThrows(RenderLimitException.class, () -> DeadlineRegex.invoke(s, "replaceAll",
+ new Object[] {"(?s)^(.*)$", "$1$1"}));
+ } finally {
+ session.end();
+ }
+ }
+
+ @Test
+ void givesTheSameResultsAsString() {
+ for (String s : TEXTS) {
+ for (String p : PATTERNS) {
+ assertEquals(s.matches(p), DeadlineRegex.invoke(s, "matches", new Object[] {p}));
+ assertArrayEquals(s.split(p),
+ (String[]) DeadlineRegex.invoke(s, "split", new Object[] {p}), s + " / " + p);
+ for (int limit : new int[] {-1, 0, 1, 2}) {
+ assertArrayEquals(s.split(p, limit),
+ (String[]) DeadlineRegex.invoke(s, "split", new Object[] {p, limit}));
+ }
+ for (String r : REPLACEMENTS) {
+ if (r.contains("$1") && !p.contains("(")) {
+ continue; // no such group: the call throws
+ }
+ assertEquals(s.replaceAll(p, r),
+ DeadlineRegex.invoke(s, "replaceAll", new Object[] {p, r}));
+ assertEquals(s.replaceFirst(p, r),
+ DeadlineRegex.invoke(s, "replaceFirst", new Object[] {p, r}));
+ }
+ }
+ }
+ }
+
+ @Test
+ void leavesOtherCallsToString() {
+ assertSame(DeadlineRegex.NOT_HANDLED, DeadlineRegex.invoke("a", "replace", new Object[] {"a", "b"}));
+ assertSame(DeadlineRegex.NOT_HANDLED, DeadlineRegex.invoke("a", "split", new Object[] {"a", true}));
+ assertSame(DeadlineRegex.NOT_HANDLED, DeadlineRegex.invoke("a", "matches", new Object[] {null}));
+ }
+
+ /** Only the pieces split returns count: it drops trailing empty ones. */
+ @Test
+ void trailingEmptyPiecesDoNotCountTowardTheLimit() {
+ int max = DeadlineRegex.MAX_SPLIT_PIECES;
+ String commas = ",".repeat(max + 50_000);
+ assertArrayEquals(commas.split(","),
+ (String[]) DeadlineRegex.invoke(commas, "split", new Object[] {","}));
+
+ String atTheLimit = "a,".repeat(max) + commas;
+ assertEquals(max,
+ ((String[]) DeadlineRegex.invoke(atTheLimit, "split", new Object[] {","})).length);
+ // empty pieces before a piece that is kept are returned, so they count
+ assertEquals(max,
+ ((String[]) DeadlineRegex.invoke(",".repeat(max - 1) + "a,,", "split",
+ new Object[] {","})).length);
+
+ assertThrows(RenderLimitException.class,
+ () -> DeadlineRegex.invoke("a," + atTheLimit, "split", new Object[] {","}));
+ assertThrows(RenderLimitException.class,
+ () -> DeadlineRegex.invoke(",".repeat(max) + "a", "split", new Object[] {","}));
+ // a negative limit keeps the trailing empty pieces
+ assertThrows(RenderLimitException.class,
+ () -> DeadlineRegex.invoke(commas, "split", new Object[] {",", -1}));
+ }
+
+ private static long allocatedBytes() {
+ return ((com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean())
+ .getThreadAllocatedBytes(Thread.currentThread().getId());
+ }
+
+ /**
+ * A replacement that takes a string at the output limit one character
+ * past it has to stop before the rest of the string is copied after it.
+ */
+ @Test
+ void theTextAfterTheLastReplacementCountsTowardTheLimit() {
+ RenderSession session = RenderSession.begin(null);
+ try {
+ String s = "0".repeat((int) session.getMaxOutputChars());
+ for (String method : new String[] {"replaceFirst", "replaceAll"}) {
+ assertThrows(RenderLimitException.class,
+ () -> DeadlineRegex.invoke(s, method, new Object[] {"^0", "xx"}));
+ long before = allocatedBytes();
+ assertThrows(RenderLimitException.class,
+ () -> DeadlineRegex.invoke(s, method, new Object[] {"^0", "xx"}));
+ long allocated = allocatedBytes() - before;
+ assertTrue(allocated < 1024 * 1024,
+ method + " allocated " + allocated + " bytes before it was stopped");
+ }
+ } finally {
+ session.end();
+ }
+ }
+}
diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitsTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitsTest.java
new file mode 100644
index 0000000000..f42faea7eb
--- /dev/null
+++ b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitsTest.java
@@ -0,0 +1,703 @@
+/*
+ * 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.
+ */
+
+package org.apache.roller.weblogger.ui.rendering.velocity;
+
+import java.lang.management.ManagementFactory;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.roller.RollerException;
+import org.apache.roller.weblogger.ui.rendering.RenderingException;
+import org.apache.roller.weblogger.ui.rendering.model.UtilitiesModel;
+import org.apache.roller.weblogger.ui.rendering.mobile.MobileDeviceRepository.DeviceType;
+import org.apache.roller.weblogger.ui.rendering.velocity.RollerVelocityTestSupport.CeilingWriter;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * A weblog template can loop, build strings and write output, so rendering
+ * one has to stop at a size and time limit instead of running until the
+ * server runs out of memory or threads. These render through the shipped
+ * engine configuration and VelocityRenderer, as the page servlets do.
+ */
+public class RenderLimitsTest {
+
+ /** Roller's default output limit, plus room for the last write. */
+ private static final long OUTPUT_LIMIT = 10L * 1024 * 1024 + 64 * 1024;
+
+ private static final Duration WITHIN = Duration.ofSeconds(30);
+
+ @BeforeAll
+ public static void setUpEngine() throws Exception {
+ RollerVelocityTestSupport.install();
+ }
+
+ private static final class Outcome {
+ CeilingWriter out = new CeilingWriter();
+ RenderingException failure;
+ }
+
+ private static Outcome render(String name, String source) throws Exception {
+ return render(name, source, new HashMap<>());
+ }
+
+ private static Outcome render(String name, String source, Map context)
+ throws Exception {
+ RollerVelocityTestSupport.addTemplate(name, source);
+ Outcome outcome = new Outcome();
+ VelocityRenderer renderer = new VelocityRenderer(
+ RollerVelocityTestSupport.page(name), DeviceType.standard);
+ try {
+ renderer.render(context, outcome.out);
+ } catch (RenderingException ex) {
+ outcome.failure = ex;
+ }
+ return outcome;
+ }
+
+ /** RenderingException keeps its cause as the root cause, not in getCause(). */
+ private static Throwable causeOf(Throwable t) {
+ return t instanceof RollerException ? ((RollerException) t).getRootCause() : t.getCause();
+ }
+
+ private static boolean reachedTestCeiling(Throwable t) {
+ for (; t != null; t = causeOf(t)) {
+ if (t instanceof IllegalStateException
+ && "test ceiling reached".equals(t.getMessage())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /** Asserts the render failed with this limit, rather than after doing the work. */
+ private static void assertLimit(Outcome outcome, String message) {
+ assertNotNull(outcome.failure, "rendering should have failed with \"" + message
+ + "\", but wrote " + outcome.out.getHead());
+ Throwable t = outcome.failure;
+ while (t != null && !(t instanceof RenderLimitException)) {
+ t = causeOf(t);
+ }
+ assertNotNull(t, "rendering failed with something other than a limit: "
+ + outcome.failure);
+ assertTrue(t.getMessage().startsWith(message), "stopped by: " + t.getMessage());
+ }
+
+ /** Renders with a smaller output limit, so a test needn't build tens of megabytes. */
+ private static Outcome renderWithLimit(String name, String source, int maxOutputChars)
+ throws Exception {
+ try (AutoCloseable limit = RollerVelocityTestSupport.property(
+ RenderSession.MAX_OUTPUT_CHARS, String.valueOf(maxOutputChars))) {
+ return render(name, source);
+ }
+ }
+
+ private static void assertStoppedByRoller(Outcome outcome) {
+ assertFalse(outcome.out.getCount() > OUTPUT_LIMIT,
+ "rendering wrote " + outcome.out.getCount() + " chars before stopping");
+ assertNotNull(outcome.failure, "rendering should have failed");
+ assertFalse(reachedTestCeiling(outcome.failure),
+ "only the test's own ceiling stopped rendering");
+ }
+
+ /**
+ * A loop longer than the limit fails the render rather than stopping
+ * quietly, which would serve and cache the page as if it were whole.
+ */
+ @Test
+ public void aHugeForeachRangeFailsAtTheLoopLimit() {
+ assertTimeoutPreemptively(WITHIN, () -> {
+ Outcome outcome = render("limits-foreach.vm",
+ "#foreach($i in [1..2000000000])0123456789#end");
+ assertLimit(outcome, "#foreach made more than 100000 passes");
+ assertTrue(outcome.out.getCount() <= 100000 * 10,
+ "#foreach ran past 100000 passes: wrote " + outcome.out.getCount());
+ });
+ }
+
+ @Test
+ public void aForeachOfExactlyTheLoopLimitCompletes() throws Exception {
+ Outcome whole = render("limits-foreach-whole.vm",
+ "#set($n = 0)#foreach($i in [1..100000])#set($n = $i)#end$n");
+ assertEquals(null, whole.failure);
+ assertEquals("100000", whole.out.getHead());
+
+ Outcome over = render("limits-foreach-over.vm",
+ "#set($n = 0)#foreach($i in [1..100001])#set($n = $i)#end$n");
+ assertLimit(over, "#foreach made more than 100000 passes");
+ }
+
+ @Test
+ public void nestedLoopsStopAtTheOutputLimit() {
+ assertTimeoutPreemptively(WITHIN, () -> assertStoppedByRoller(render(
+ "limits-nested.vm",
+ "#foreach($i in [1..100000])#foreach($j in [1..100000])"
+ + "0123456789#end#end")));
+ }
+
+ @Test
+ public void limitsApplyInsideMacrosAndParsedTemplates() {
+ RollerVelocityTestSupport.addTemplate("limits-parsed.vm", "#spin()");
+ assertTimeoutPreemptively(WITHIN, () -> assertStoppedByRoller(render(
+ "limits-macro.vm",
+ "#macro(spin)#foreach($i in [1..100000])#foreach($j in [1..100000])"
+ + "0123456789#end#end#end#parse('limits-parsed.vm')")));
+ }
+
+ @Test
+ public void aLoopThatWritesNothingStopsAtTheDeadline() {
+ assertTimeoutPreemptively(WITHIN, () -> {
+ Outcome outcome = render("limits-deadline.vm",
+ "#foreach($i in [1..100000])#foreach($j in [1..100000])"
+ + "#set($k = $j)#end#end");
+ assertNotNull(outcome.failure, "rendering should have failed");
+ });
+ }
+
+ @Test
+ public void aStringDoubledInPlaceStopsAtTheSizeLimit() {
+ assertTimeoutPreemptively(WITHIN, () -> {
+ Outcome outcome = render("limits-doubling.vm",
+ "#set($s = '0123456789')"
+ + "#foreach($i in [1..22])#set($s = \"$s$s\")#end$s.length()");
+ assertNotNull(outcome.failure,
+ "rendering should have failed, but wrote " + outcome.out.getHead());
+ });
+ }
+
+ @Test
+ public void stringRepeatIsNotAvailableToTemplates() {
+ assertTimeoutPreemptively(WITHIN, () -> {
+ Outcome outcome = render("limits-repeat.vm",
+ "#set($s = '0123456789')"
+ + "$s.repeat(3000000)$s.repeat(3000000)$s.repeat(3000000)");
+ assertFalse(reachedTestCeiling(outcome.failure),
+ "String.repeat filled the output");
+ assertTrue(outcome.out.getCount() < 1024 * 1024,
+ "String.repeat wrote " + outcome.out.getCount() + " chars");
+ assertFalse(outcome.out.getHead().contains("01234567890123456789"),
+ "String.repeat ran: " + outcome.out.getHead());
+ });
+ }
+
+ /** The limits are chained after SecureUberspector, which still applies. */
+ @Test
+ public void theIntrospectionSandboxStillApplies() throws Exception {
+ Outcome outcome = render("limits-sandbox.vm",
+ "#set($s = 'x')[$s.class.classLoader]"
+ + "[$s.getClass().forName('java.lang.Runtime')]");
+ assertEquals("[$s.class.classLoader][$s.getClass().forName('java.lang.Runtime')]",
+ outcome.out.getHead());
+ }
+
+ /** A 10,240-character string of digits, 1,024 of them zeros. */
+ private static final String TEN_THOUSAND_DIGITS = "#set($s = '0123456789')"
+ + "#foreach($i in [1..10])#set($s = \"$s$s\")#end";
+
+ private static long allocatedBytes() {
+ return ((com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean())
+ .getThreadAllocatedBytes(Thread.currentThread().getId());
+ }
+
+ /**
+ * Renders on this thread and returns how many bytes the render allocated,
+ * after a first render that loads the engine and compiles the template.
+ */
+ private static long allocatedByRender(String name, String source,
+ Map context) throws Exception {
+ Outcome warmUp = render(name, source, context);
+ assertNotNull(warmUp.failure, "rendering should have failed");
+ long before = allocatedBytes();
+ Outcome outcome = render(name, source, context);
+ long allocated = allocatedBytes() - before;
+ assertNotNull(outcome.failure, "rendering should have failed");
+ assertFalse(reachedTestCeiling(outcome.failure),
+ "only the test's own ceiling stopped rendering");
+ return allocated;
+ }
+
+ /**
+ * Each of these would build a string of about 42 million characters, four
+ * times the output limit. The call has to be refused before it runs, not
+ * after the result is built.
+ */
+ @Test
+ public void growingStringCallsAreRefusedBeforeTheyRun() throws Exception {
+ String[] calls = {
+ "$s.replace('0', \"$s$s$s$s\")",
+ "$s.replaceAll('0', \"$s$s$s$s\")",
+ "$utils.replace($s, '0', \"$s$s$s$s\")",
+ };
+ Map context = new HashMap<>();
+ context.put("utils", new UtilitiesModel());
+ for (int i = 0; i < calls.length; i++) {
+ long allocated = allocatedByRender("limits-growing-" + i + ".vm",
+ TEN_THOUSAND_DIGITS + calls[i], context);
+ // replaceAll builds part of the result before it stops; without
+ // the checks each of these allocates over 100 MB
+ assertTrue(allocated < 64L * 1024 * 1024,
+ calls[i] + " allocated " + allocated + " bytes before it was stopped");
+ }
+ }
+
+ /**
+ * $utils methods that escape or encode text can make each character
+ * several, so they too have to be refused before they run. Each of these
+ * on 6,291,456 characters would build at least twice the output limit.
+ */
+ @Test
+ public void expandingUtilityCallsAreRefusedBeforeTheyRun() throws Exception {
+ String[] calls = {
+ "$utils.escapeHTML($s)",
+ "$utils.escapeXML($s)",
+ "$utils.escapeJavaScript($s)",
+ "$utils.encode($s)",
+ "$utils.hexEncode($s)",
+ "$utils.autoformat($s)",
+ };
+ Map context = new HashMap<>();
+ context.put("utils", new UtilitiesModel());
+ String setup = "#set($s = \"<\u00e9\n\")#foreach($i in [1..21])#set($s = \"$s$s\")#end";
+ // building the string alone, without the call
+ String baselineName = "limits-expanding-baseline.vm";
+ render(baselineName, setup + "$s.length()", context);
+ long before = allocatedBytes();
+ Outcome baseline = render(baselineName, setup + "$s.length()", context);
+ long building = allocatedBytes() - before;
+ assertEquals(null, baseline.failure);
+ for (int i = 0; i < calls.length; i++) {
+ long allocated = allocatedByRender("limits-expanding-" + i + ".vm",
+ setup + calls[i], context) - building;
+ // without the checks each call allocates at least 25 MB more
+ assertTrue(allocated < 16L * 1024 * 1024,
+ calls[i] + " allocated " + allocated + " bytes before it was stopped");
+ }
+ }
+
+ /** A case change of a large ASCII string fits whenever the string does. */
+ @Test
+ public void caseChangesOfALargeAsciiStringStillWork() throws Exception {
+ Map context = new HashMap<>();
+ context.put("utils", new UtilitiesModel());
+ Outcome outcome = render("limits-case.vm", FIVE_MILLION_DIGITS
+ + "$s.toUpperCase().length() $s.toLowerCase().length()"
+ + " $utils.toUpperCase($s).length() $utils.escapeHTML($s).length()",
+ context);
+ assertEquals(null, outcome.failure);
+ assertEquals("5242880 5242880 5242880 5242880", outcome.out.getHead());
+ }
+
+ /**
+ * A string just under the output limit split into one-character pieces
+ * would allocate millions of strings before anything checks their size,
+ * so a split may return no more pieces than a #foreach can visit.
+ */
+ @Test
+ public void splittingIntoMorePiecesThanALoopCanVisitIsRefused() throws Exception {
+ // 10,485,760 characters, just under the output limit
+ String nearTheLimit = TEN_THOUSAND_DIGITS
+ + "#foreach($i in [1..10])#set($s = \"$s$s\")#end";
+ long allocated = allocatedByRender("limits-split.vm",
+ nearTheLimit + "$s.split('').size()", new HashMap<>());
+ // the string itself takes about 40 MB to build; the pieces would add
+ // over 500 MB
+ assertTrue(allocated < 160L * 1024 * 1024,
+ "split allocated " + allocated + " bytes before it was stopped");
+
+ Outcome ordinary = render("limits-split-ordinary.vm",
+ TEN_THOUSAND_DIGITS + "$s.split('0').size() $s.split('', 3).size()");
+ assertEquals(null, ordinary.failure);
+ assertEquals("1025 3", ordinary.out.getHead());
+ }
+
+ /** String.format can pad to any width, so it is not offered. */
+ @Test
+ public void stringFormatIsNotAvailableToTemplates() throws Exception {
+ Outcome outcome = render("limits-format.vm",
+ "#set($s = 'x')$s.format('%05000000d', 1)");
+ assertFalse(outcome.out.getHead().contains("00000000"),
+ "String.format ran");
+ assertTrue(outcome.out.getCount() < 1024, "String.format wrote "
+ + outcome.out.getCount() + " chars");
+ }
+
+ @Test
+ public void ordinaryStringCallsStillWork() throws Exception {
+ Map context = new HashMap<>();
+ context.put("utils", new UtilitiesModel());
+ Outcome outcome = render("limits-ordinary.vm",
+ "#set($s = 'Hello, World')"
+ + "[$s.replace('o', '0')][$s.replace('', '-')][$s.replaceAll('[A-Z]', '_')]"
+ + "[$s.replaceFirst('l+', 'L')][$s.concat('!')][$s.toUpperCase()]"
+ + "[$s.toLowerCase()][$s.substring(7)][$s.trim()]"
+ + "[$utils.replace($s, ' ', '_')]",
+ context);
+ assertEquals(null, outcome.failure);
+ assertEquals("[Hell0, W0rld][-H-e-l-l-o-,- -W-o-r-l-d-][_ello, _orld]"
+ + "[HeLo, World][Hello, World!][HELLO, WORLD]"
+ + "[hello, world][World][Hello, World]"
+ + "[Hello,_World]", outcome.out.getHead());
+ }
+
+ @Test
+ public void ordinaryLiteralsSumsBlocksAndExpressionsStillWork() throws Exception {
+ Outcome outcome = render("limits-ordinary-literals.vm",
+ "#set($a = 'x')#set($b = \"[$a$a]\")#set($c = $a + $b + 1)"
+ + "#define($d)<#if($a)$a#end>#end#set($e = $d + '')"
+ + "#macro(wrap)($bodyContent)#end"
+ + "$b|$c|$d|$e|#@wrap()$a#end|$a.matches('x')|$c.split('\\[').size()"
+ + "|$c.replaceAll('[x]', 'y')");
+ assertEquals(null, outcome.failure);
+ assertEquals("[xx]|x[xx]1|||(x)|true|2|y[yy]1", outcome.out.getHead());
+ }
+
+ /** A string of 5,242,880 digits, half the output limit. */
+ private static final String FIVE_MILLION_DIGITS = "#set($s = '0123456789')"
+ + "#foreach($i in [1..19])#set($s = \"$s$s\")#end";
+
+ /** About 30 million characters of text, from loops that insert nothing. */
+ private static final String THIRTY_MILLION_CHARS =
+ "#foreach($i in [1..100000])#foreach($j in [1..30])0123456789#end#end";
+
+ private static void assertStoppedInMemory(String name, String source) throws Exception {
+ Outcome outcome = render(name, source);
+ assertNotNull(outcome.failure, name + " should have failed, but wrote "
+ + outcome.out.getCount() + " chars");
+ assertFalse(reachedTestCeiling(outcome.failure),
+ "only the test's own ceiling stopped rendering");
+ assertTrue(outcome.out.getCount() < 1024, name + " wrote " + outcome.out.getCount());
+ }
+
+ @Test
+ public void aStringDoubledWithPlusStopsAtTheSizeLimit() throws Exception {
+ assertStoppedInMemory("limits-plus-doubling.vm", "#set($s = '0123456789')"
+ + "#foreach($i in [1..22])#set($s = $s + $s)#end$s.length()");
+ }
+
+ @Test
+ public void oneLongSumStopsAtTheSizeLimit() throws Exception {
+ assertStoppedInMemory("limits-plus-sum.vm", FIVE_MILLION_DIGITS
+ + "#set($t = $s + $s + $s + $s)$t.length()");
+ }
+
+ @Test
+ public void aStringLiteralWithManyReferencesStopsAtTheSizeLimit() throws Exception {
+ assertStoppedInMemory("limits-literal-refs.vm", FIVE_MILLION_DIGITS
+ + "#set($t = \"$s$s$s$s\")$t.length()");
+ }
+
+ @Test
+ public void loopsInsideAStringLiteralStopAtTheSizeLimit() throws Exception {
+ assertStoppedInMemory("limits-literal-loops.vm",
+ "#set($t = \"" + THIRTY_MILLION_CHARS + "\")$t.length()");
+ }
+
+ @Test
+ public void aDefinedBlockTurnedIntoAStringStopsAtTheSizeLimit() throws Exception {
+ assertStoppedInMemory("limits-define.vm",
+ "#define($b)" + THIRTY_MILLION_CHARS + "#end#set($t = $b + '')$t.length()");
+ }
+
+ @Test
+ public void macroRecursionThatWritesNothingStopsAtTheDeadline() throws Exception {
+ long start = System.nanoTime();
+ // four calls a level, 13 levels deep: about 90 million calls
+ String call = "#set($e = $d - 1)#spin($e)";
+ Outcome outcome = render("limits-macro-recursion.vm",
+ "#macro(spin $d)#if($d > 0)" + call + call + call + call + "#end#end"
+ + "#spin(13)done");
+ long seconds = (System.nanoTime() - start) / 1_000_000_000L;
+ assertNotNull(outcome.failure, "rendering should have failed after "
+ + seconds + " seconds, but wrote " + outcome.out.getHead());
+ assertTrue(seconds < 10, "rendering took " + seconds + " seconds");
+ }
+
+ @Test
+ public void aSlowRegularExpressionStopsAtTheDeadline() throws Exception {
+ String[] calls = {"$s.matches('(.*a){12}b')", "$s.split('(.*a){12}b', 2)"};
+ for (int i = 0; i < calls.length; i++) {
+ long start = System.nanoTime();
+ Outcome outcome = render("limits-regex-" + i + ".vm",
+ "#set($s = '" + "a".repeat(36) + "')[" + calls[i] + "]");
+ long seconds = (System.nanoTime() - start) / 1_000_000_000L;
+ assertNotNull(outcome.failure, calls[i] + " should have failed, but wrote "
+ + outcome.out.getHead() + " in " + seconds + " seconds");
+ assertTrue(seconds < 10, calls[i] + " took " + seconds + " seconds");
+ }
+ }
+
+ @Test
+ public void aRegexReplaceWithGroupsOnALongStringStillWorks() throws Exception {
+ Outcome outcome = render("limits-regex-groups.vm", TEN_THOUSAND_DIGITS
+ + "#set($r = $s.replaceAll('(\\d)', '<$1>'))$r.length() $r.substring(0, 9)");
+ assertEquals(null, outcome.failure);
+ assertEquals("30720 <0><1><2>", outcome.out.getHead());
+ }
+
+ /**
+ * Velocity asks a node for its template's name to say where something
+ * went wrong, so the nodes the parser swaps in have to know it too.
+ */
+ @Test
+ public void arithmeticOnAnUndefinedReferenceStillRenders() throws Exception {
+ Outcome outcome = render("limits-undefined-sum.vm",
+ "#set($x = $undefined + 1)ok");
+ assertEquals(null, outcome.failure);
+ assertEquals("ok", outcome.out.getHead());
+ }
+
+ @Test
+ public void endlessMacroRecursionStopsAtTheDepthLimit() throws Exception {
+ Outcome outcome = render("limits-macro-depth.vm", "#macro(r)#r()#end#r()");
+ // Velocity's own error for a macro that calls itself too deeply gets
+ // the renderer's error page
+ assertEquals(null, outcome.failure);
+ assertTrue(outcome.out.getHead().contains(""),
+ "rendering wrote " + outcome.out.getHead());
+ }
+
+ /** 81,920 characters, for tests with a limit of 100,000. */
+ private static final String EIGHTY_THOUSAND_DIGITS = "#set($s = '0123456789')"
+ + "#foreach($i in [1..13])#set($s = \"$s$s\")#end";
+
+ /** A list or map is checked as text before Velocity turns it into one string. */
+ @Test
+ public void aLargeListIsRefusedBeforeItIsWrittenAsText() throws Exception {
+ String[] uses = {
+ "$r",
+ "$r.toString()",
+ "#set($t = '' + $r)",
+ "#set($s = 'x')$s.valueOf($r)",
+ "#if($r == 'x')yes#end",
+ "#set($m = {'k': $r})$m",
+ "#set($m = {'k': $r})$m.entrySet()",
+ "#set($m = {'k': $r})#foreach($e in $m.entrySet())$e#end",
+ };
+ for (int i = 0; i < uses.length; i++) {
+ Outcome outcome = renderWithLimit("limits-list-text-" + i + ".vm",
+ "#set($r = [1..2000000])" + uses[i], 100_000);
+ assertLimit(outcome, "a string would be longer than 100000 characters");
+ }
+ }
+
+ @Test
+ public void aDeeplyNestedListIsRefusedBeforeItIsWrittenAsText() throws Exception {
+ Outcome outcome = renderWithLimit("limits-nested-list.vm",
+ "#set($l = [1])#foreach($i in [1..20])#set($l = [$l, $l])#end$l", 100_000);
+ assertLimit(outcome, "a string would be longer than 100000 characters");
+ }
+
+ @Test
+ public void smallListsAndMapsStillPrint() throws Exception {
+ Outcome outcome = render("limits-list-ordinary.vm",
+ "#set($l = [1, 'two', [3]])#set($m = {'a': 1})"
+ + "#set($x = $l.add($l))$l $m ${l.size()} #if($m != 'x')ne#end");
+ assertEquals(null, outcome.failure);
+ assertEquals("[1, two, [3], (this Collection)] {a=1} 4 ne", outcome.out.getHead());
+ }
+
+ @Test
+ public void aTemplateThatBuildsAHugeListStopsAtTheLimit() throws Exception {
+ Outcome doubled = render("limits-list-doubling.vm",
+ "#set($l = [1])#foreach($i in [1..21])#set($x = $l.addAll($l))#end$l.size()");
+ assertLimit(doubled, "rendering added more than 1000000 items");
+
+ // the range is refused before any of it is copied
+ Outcome copied = render("limits-list-copy.vm",
+ "#set($l = [])#set($x = $l.addAll([1..1000001]))$l.size()");
+ assertLimit(copied, "rendering added more than 1000000 items");
+
+ Outcome array = render("limits-list-array.vm",
+ "#set($r = [1..1000001])#set($a = $r.toArray())$a.size()");
+ assertLimit(array, "rendering added more than 1000000 items");
+
+ // adding a large list as one item is one item
+ Outcome one = render("limits-list-one.vm",
+ "#set($l = [])#set($x = $l.add([1..2000000]))$l.size() ${l.get(0).size()}");
+ assertEquals(null, one.failure);
+ assertEquals("1 2000000", one.out.getHead());
+
+ Outcome map = render("limits-map.vm",
+ "#set($m = {})#foreach($i in [1..1000])#foreach($j in [1..1001])"
+ + "#set($x = $m.put(\"$i-$j\", $j))#end#end$m.size()");
+ assertLimit(map, "rendering added more than 1000000 items");
+ }
+
+ @Test
+ public void aTemplateThatKeepsManyLongStringsStopsAtTheLimit() throws Exception {
+ // each string is new, so the list would hold 50 times 81,920 characters
+ Outcome outcome = renderWithLimit("limits-kept-strings.vm", EIGHTY_THOUSAND_DIGITS
+ + "#set($l = [])#foreach($i in [1..50])#set($x = $l.add(\"$s$i\"))#end"
+ + "$l.size()", 100_000);
+ assertLimit(outcome, "rendering built more than 1000000 characters of strings");
+ }
+
+ @Test
+ public void comparingTwoLargeListsElementByElementIsRefused() throws Exception {
+ Outcome outcome = render("limits-contains-all.vm",
+ "#set($a = [1..100000])#set($b = [1..200])$a.containsAll($b)");
+ assertLimit(outcome, "containsAll would compare more than 10000000 pairs");
+
+ Outcome ordinary = render("limits-contains-all-ordinary.vm",
+ "#set($a = [1..1000])#set($b = [1..200])$a.containsAll($b)");
+ assertEquals(null, ordinary.failure);
+ assertEquals("true", ordinary.out.getHead());
+ }
+
+ @Test
+ public void aTemplateThatBuildsAHugeNumberStopsAtTheLimit() throws Exception {
+ String big = "#set($b = 9223372036854775807 + 1)";
+ String[] growth = {
+ "$b.shiftLeft(200000)",
+ "$b.pow(5000)",
+ "$b.setBit(200000)",
+ "#foreach($i in [1..15])#set($b = $b * $b)#end",
+ };
+ for (int i = 0; i < growth.length; i++) {
+ Outcome outcome = render("limits-number-" + i + ".vm", big + growth[i]);
+ assertLimit(outcome, "a number would have more than 100000 bits");
+ }
+ Outcome prime = render("limits-number-prime.vm", big + "$b.isProbablePrime(50)");
+ assertLimit(prime, "isProbablePrime is not available to templates");
+
+ Outcome ordinary = render("limits-number-ordinary.vm", big + "$b.shiftLeft(2) ${b.pow(2)}");
+ assertEquals(null, ordinary.failure);
+ assertEquals("36893488147419103232 85070591730234615865843651857942052864",
+ ordinary.out.getHead());
+ }
+
+ @Test
+ public void utilitiesSplitIntoMorePiecesThanALoopCanVisitIsRefused() throws Exception {
+ Map context = new HashMap<>();
+ context.put("utils", new UtilitiesModel());
+ context.put("s", "a,".repeat(150_000));
+ Outcome outcome = render("limits-utils-split.vm", "$utils.split($s, ',').size()",
+ context);
+ assertLimit(outcome, "split produced more than 100000 pieces");
+
+ context.put("s", ",,a,,b,c,,");
+ Outcome ordinary = render("limits-utils-split-ordinary.vm",
+ "$utils.split($s, ',').size()", context);
+ assertEquals(null, ordinary.failure);
+ assertEquals("3", ordinary.out.getHead());
+ }
+
+ @Test
+ public void stringMethodsThatSplitWithoutTheLimitsAreNotAvailable() throws Exception {
+ Outcome outcome = render("limits-split-delimiters.vm",
+ "#set($s = 'a,b')[$s.splitWithDelimiters(',', 0)][$s.lines()]");
+ assertEquals(null, outcome.failure);
+ assertEquals("[$s.splitWithDelimiters(',', 0)][$s.lines()]", outcome.out.getHead());
+ }
+
+ /** Velocity calls a class's static methods on its Class object. */
+ @Test
+ public void staticStringMethodsAreNotAvailableThroughTheClass() throws Exception {
+ Outcome outcome = render("limits-class-static.vm",
+ "#set($s = 'x')[$s.class.format('%s', 'y')][$s.getClass().join('-', ['a'])]"
+ + "[$s.class.name][$s.getClass().getName()]");
+ assertEquals(null, outcome.failure);
+ assertEquals("[$s.class.format('%s', 'y')][$s.getClass().join('-', ['a'])]"
+ + "[java.lang.String][java.lang.String]", outcome.out.getHead());
+ }
+
+ /**
+ * A replace with a group that doesn't exist, or with no replacement,
+ * shows the template error page as before, rather than failing the page.
+ */
+ @Test
+ public void aRegexReplaceTheStringMethodRefusesShowsTheTemplateError() throws Exception {
+ String[] calls = {"$s.replaceAll('b', '$1')", "$s.replaceAll('b', $nothing)",
+ "$s.replaceFirst('x', $nothing)"};
+ for (int i = 0; i < calls.length; i++) {
+ Outcome outcome = render("limits-regex-error-" + i + ".vm",
+ "#set($s = 'abc')[" + calls[i] + "]");
+ assertEquals(null, outcome.failure, calls[i]);
+ assertTrue(outcome.out.getHead().contains(""),
+ calls[i] + " wrote " + outcome.out.getHead());
+ }
+ Outcome nothingToReplace = render("limits-regex-null-unmatched.vm",
+ "#set($s = 'abc')[$s.replaceAll('x', $nothing)]");
+ assertEquals(null, nothingToReplace.failure);
+ assertEquals("[abc]", nothingToReplace.out.getHead());
+ }
+
+ @Test
+ public void aRegexThatRepeatsAnEmptyMatchIsRefused() throws Exception {
+ Outcome outcome = render("limits-regex-empty.vm",
+ "#set($s = '')$s.matches('(?:a?|b?)(?:a?|b?)c')");
+ assertLimit(outcome, "a regular expression repeats a part that can match an empty");
+ }
+
+ /** A template error can quote a long value, which the error page shortens. */
+ @Test
+ public void aTemplateErrorAboutALongValueStaysShort() throws Exception {
+ Outcome outcome = render("limits-long-error.vm", TEN_THOUSAND_DIGITS
+ + "#set($t = \"x$s\")#set($i = 1)$i.parseInt($t)");
+ assertEquals(null, outcome.failure);
+ assertTrue(outcome.out.getHead().contains(""),
+ "rendering wrote " + outcome.out.getHead());
+ assertTrue(outcome.out.getCount() < 5000, "the error page wrote "
+ + outcome.out.getCount() + " chars");
+ }
+
+ @Test
+ public void aBlankOrInvalidLimitFallsBackToTheDefault() throws Exception {
+ for (String value : new String[] {"", " ", "ten"}) {
+ try (AutoCloseable limit = RollerVelocityTestSupport.property(
+ RenderSession.MAX_OUTPUT_CHARS, value)) {
+ RenderSession session = RenderSession.begin(null);
+ try {
+ assertEquals(10L * 1024 * 1024, session.getMaxOutputChars(), value);
+ } finally {
+ session.end();
+ }
+ }
+ }
+ }
+
+ @Test
+ public void aSessionStartedInsideAnotherSharesItsBudget() throws Exception {
+ try (AutoCloseable limit = RollerVelocityTestSupport.property(
+ RenderSession.MAX_OUTPUT_CHARS, "1000")) {
+ RenderSession outer = RenderSession.begin(null);
+ try {
+ RenderSession.chargeBuilt(9000);
+ RenderSession inner = RenderSession.begin(null);
+ try {
+ assertThrows(RenderLimitException.class,
+ () -> RenderSession.chargeBuilt(2000));
+ } finally {
+ inner.end();
+ }
+ } finally {
+ outer.end();
+ }
+ }
+ }
+}
diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerVelocityTestSupport.java b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerVelocityTestSupport.java
new file mode 100644
index 0000000000..ca2e9606b9
--- /dev/null
+++ b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerVelocityTestSupport.java
@@ -0,0 +1,196 @@
+/*
+ * 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.
+ */
+
+package org.apache.roller.weblogger.ui.rendering.velocity;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.Writer;
+import java.lang.reflect.Field;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Date;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.ConcurrentHashMap;
+
+import javax.servlet.ServletContext;
+
+import org.apache.roller.weblogger.config.WebloggerConfig;
+import org.apache.roller.weblogger.pojos.Template;
+import org.apache.roller.weblogger.pojos.TemplateRendition;
+import org.apache.roller.weblogger.pojos.TemplateRendition.RenditionType;
+import org.apache.roller.weblogger.ui.core.RollerContext;
+
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * Lets tests drive the real {@link RollerVelocity} engine, configured from the
+ * shipped WEB-INF/velocity.properties, without a servlet container. Files under
+ * src/main/webapp are served as they are; a test can add its own templates,
+ * which are served from /WEB-INF/velocity/ by name.
+ */
+final class RollerVelocityTestSupport {
+
+ private static final Path WEBAPP = Paths.get(
+ System.getProperty("project.basedir", System.getProperty("user.dir")),
+ "src", "main", "webapp");
+
+ private static final String TEMPLATE_DIR = "/WEB-INF/velocity/";
+
+ private static final Map TEMPLATES = new ConcurrentHashMap<>();
+
+ private static boolean installed = false;
+
+ private RollerVelocityTestSupport() {
+ }
+
+ /** Points RollerContext at a servlet context that serves the webapp. */
+ static synchronized void install() throws Exception {
+ if (installed) {
+ return;
+ }
+ ServletContext context = mock(ServletContext.class);
+ when(context.getResourceAsStream(anyString()))
+ .thenAnswer(inv -> open(inv.getArgument(0)));
+ Field field = RollerContext.class.getDeclaredField("servletContext");
+ field.setAccessible(true);
+ field.set(null, context);
+ installed = true;
+ }
+
+ /**
+ * Sets a Roller property, or removes it when value is null, until the
+ * returned handle is closed, which puts the old value back.
+ */
+ static AutoCloseable property(String name, String value) throws Exception {
+ Field field = WebloggerConfig.class.getDeclaredField("config");
+ field.setAccessible(true);
+ Properties config = (Properties) field.get(null);
+ String old = config.getProperty(name);
+ set(config, name, value);
+ return () -> set(config, name, old);
+ }
+
+ private static void set(Properties config, String name, String value) {
+ if (value == null) {
+ config.remove(name);
+ } else {
+ config.setProperty(name, value);
+ }
+ }
+
+ /** Adds a template the engine can load by name. Names must be unique. */
+ static void addTemplate(String name, String source) {
+ TEMPLATES.put(name, source);
+ }
+
+ private static InputStream open(String path) throws IOException {
+ if (path.startsWith(TEMPLATE_DIR)) {
+ String source = TEMPLATES.get(path.substring(TEMPLATE_DIR.length()));
+ if (source != null) {
+ return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
+ }
+ }
+ Path file = WEBAPP.resolve(path.substring(1)).normalize();
+ if (file.startsWith(WEBAPP) && Files.isRegularFile(file)) {
+ return Files.newInputStream(file);
+ }
+ return null;
+ }
+
+ /** A page template known to the renderer only by its id. */
+ static Template page(final String id) {
+ return new Template() {
+ @Override
+ public String getId() {
+ return id;
+ }
+
+ @Override
+ public String getName() {
+ return id;
+ }
+
+ @Override
+ public String getDescription() {
+ return id;
+ }
+
+ @Override
+ public Date getLastModified() {
+ return new Date();
+ }
+
+ @Override
+ public String getOutputContentType() {
+ return null;
+ }
+
+ @Override
+ public TemplateRendition getTemplateRendition(RenditionType type) {
+ return null;
+ }
+ };
+ }
+
+ /**
+ * Collects output up to a ceiling well above Roller's own limit, so a
+ * render the limit fails to stop still ends, and the test can say so.
+ */
+ static final class CeilingWriter extends Writer {
+
+ static final long CEILING = 64L * 1024 * 1024;
+
+ private long count = 0;
+ private final StringBuilder head = new StringBuilder();
+
+ @Override
+ public void write(char[] cbuf, int off, int len) {
+ count += len;
+ if (head.length() < 4096) {
+ head.append(cbuf, off, Math.min(len, 4096 - head.length()));
+ }
+ if (count > CEILING) {
+ throw new IllegalStateException("test ceiling reached");
+ }
+ }
+
+ long getCount() {
+ return count;
+ }
+
+ String getHead() {
+ return head.toString();
+ }
+
+ @Override
+ public void flush() {
+ }
+
+ @Override
+ public void close() {
+ }
+ }
+}
diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java
new file mode 100644
index 0000000000..4ca7ea08ea
--- /dev/null
+++ b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java
@@ -0,0 +1,329 @@
+/*
+ * 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.
+ */
+
+package org.apache.roller.weblogger.ui.rendering.velocity;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.UnaryOperator;
+
+import org.apache.roller.weblogger.ui.rendering.model.UtilitiesModel;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The bound worked out before a string call has to be at least the length the
+ * call really produces. These run each call on small strings and compare.
+ */
+class StringGrowthTest {
+
+ private static final String[] TEXTS = {"", "a", "ab", "aaaa", "Hello, World", "ßßß ff İ",
+ "I\u0300 J\u0301 \u00CC Ii"};
+ private static final String[] REPLACEMENTS = {"", "x", "xyz", "$0", "$1$1", "${g}", "\\$"};
+
+ private static void assertBounds(String what, String actual, long bound) {
+ assertTrue(bound >= actual.length(),
+ what + " produced " + actual.length() + " chars, bound was " + bound);
+ }
+
+ @Test
+ void literalReplaceIsExact() {
+ for (String s : TEXTS) {
+ for (String target : REPLACEMENTS) {
+ for (String r : REPLACEMENTS) {
+ String actual = s.replace(target, r);
+ long bound = StringGrowth.maxResultLength(s, "replace", new Object[] {target, r});
+ assertEquals(Math.max(s.length(), actual.length()), bound,
+ "'" + s + "'.replace('" + target + "', '" + r + "')");
+ }
+ }
+ }
+ }
+
+ @Test
+ void caseChangesAndConcatAreBounded() {
+ for (String s : TEXTS) {
+ for (Locale l : new Locale[] {Locale.ROOT, new Locale("tr"), Locale.GERMAN,
+ new Locale("lt")}) {
+ assertBounds("toUpperCase", s.toUpperCase(l),
+ StringGrowth.maxResultLength(s, "toUpperCase", new Object[] {l}));
+ assertBounds("toLowerCase", s.toLowerCase(l),
+ StringGrowth.maxResultLength(s, "toLowerCase", new Object[] {l}));
+ }
+ assertBounds("concat", s.concat(s),
+ StringGrowth.maxResultLength(s, "concat", new Object[] {s}));
+ }
+ }
+
+ /** Each character's case change, in the locales whose rules differ, fits its bound. */
+ @Test
+ void caseChangesOfEveryCharAreBounded() {
+ List texts = everyChar();
+ texts.add("I\u0300J\u0301\u012e\u0303");
+ for (String s : texts) {
+ long bound = StringGrowth.maxResultLength(s, "toUpperCase", new Object[0]);
+ for (Locale l : new Locale[] {Locale.ROOT, new Locale("tr"), new Locale("az"),
+ new Locale("lt"), Locale.GERMAN}) {
+ assertBounds("toUpperCase", s.toUpperCase(l), bound);
+ assertBounds("toLowerCase", s.toLowerCase(l), bound);
+ }
+ }
+ }
+
+ /** Most letters outside ASCII keep their length, so large text in them still fits. */
+ @Test
+ void caseChangesOfTextOutsideAsciiAreNotOverestimated() {
+ String text = "\u041f\u0440\u0438\u0432\u0435\u0442 \u4f60\u597d \u3053\u3093";
+ assertEquals(text.length(), StringGrowth.maxResultLength(text, "toUpperCase",
+ new Object[0]));
+ assertEquals(text.length(), StringGrowth.maxResultLength(new UtilitiesModel(),
+ "toUpperCase", new Object[] {text}));
+ }
+
+ /** Escaping counts what each character becomes, so the bound is the result's length. */
+ @Test
+ void escapingIsExact() {
+ UtilitiesModel utils = new UtilitiesModel();
+ String html = "a&b \"c\" d'e \u00e9
";
+ assertEquals(utils.escapeHTML(html).length(),
+ StringGrowth.maxResultLength(utils, "escapeHTML", new Object[] {html}));
+ assertEquals(utils.escapeXML(html).length(),
+ StringGrowth.maxResultLength(utils, "escapeXML", new Object[] {html}));
+ }
+
+ /** A case change only adds characters for characters outside ASCII. */
+ @Test
+ void caseChangesOfAsciiAreNotOverestimated() {
+ String s = "Hello, World 0123456789";
+ assertEquals(s.length(), StringGrowth.maxResultLength(s, "toUpperCase", new Object[0]));
+ assertEquals(s.length(), StringGrowth.maxResultLength(s, "toLowerCase",
+ new Object[] {Locale.ROOT}));
+ }
+
+ /** Every char on its own, a surrogate pair, and all of them in one string. */
+ private static List everyChar() {
+ List texts = new ArrayList<>();
+ StringBuilder all = new StringBuilder();
+ for (int c = 0; c <= 0xFFFF; c++) {
+ texts.add(String.valueOf((char) c));
+ all.append((char) c);
+ }
+ texts.add("\uD83D\uDE00");
+ texts.add("x\uD83Dy");
+ texts.add(all.toString());
+ return texts;
+ }
+
+ /** UtilitiesModel methods that take one string, keyed by name. */
+ private static Map> oneStringCalls(UtilitiesModel utils) {
+ Map> calls = new LinkedHashMap<>();
+ calls.put("toUpperCase", utils::toUpperCase);
+ calls.put("escapeHTML", utils::escapeHTML);
+ calls.put("unescapeHTML", utils::unescapeHTML);
+ calls.put("escapeXML", utils::escapeXML);
+ calls.put("unescapeXML", utils::unescapeXML);
+ calls.put("escapeJavaScript", utils::escapeJavaScript);
+ calls.put("unescapeJavaScript", utils::unescapeJavaScript);
+ calls.put("removeHTML", utils::removeHTML);
+ calls.put("autoformat", utils::autoformat);
+ calls.put("hexEncode", utils::hexEncode);
+ calls.put("encodeEmail", utils::encodeEmail);
+ calls.put("encode", utils::encode);
+ calls.put("decode", utils::decode);
+ calls.put("addNofollow", utils::addNofollow);
+ calls.put("transformToHTMLSubset", utils::transformToHTMLSubset);
+ return calls;
+ }
+
+ private static void assertUtilityBounds(UtilitiesModel utils, String name, String actual,
+ Object... args) {
+ long longestArg = 0;
+ for (Object arg : args) {
+ longestArg = Math.max(longestArg, arg instanceof CharSequence
+ ? ((CharSequence) arg).length() : 0);
+ }
+ long bound = StringGrowth.maxResultLength(utils, name, args);
+ assertTrue(actual == null || Math.max(bound, longestArg) >= actual.length(),
+ name + " produced " + (actual == null ? 0 : actual.length())
+ + " chars, bound was " + bound);
+ }
+
+ @Test
+ void utilitiesStringCallsAreBounded() {
+ UtilitiesModel utils = new UtilitiesModel();
+ List texts = new ArrayList<>(everyChar());
+ texts.add("a<b>b</b><a href='http://x/\u00e9"&'>y</a>"
+ + "<a href=\"mailto:\u03d1é&\"><br />"");
+ texts.add(" ");
+ // links with no rel, with an unquoted or unclosed rel, and with one to add to
+ texts.add(" ".repeat(20) + " z "
+ + " ");
+ texts.add("mailto:a.b-c@d.example.org, mailto:a.b-c@d.example.org and x@y.z w@v.u.");
+ texts.add("\\u0041 \\x41 \\101 %41 %E2%82%AC 😀 ϑ ");
+ for (Map.Entry> call : oneStringCalls(utils).entrySet()) {
+ for (String s : texts) {
+ String actual;
+ try {
+ actual = call.getValue().apply(s);
+ } catch (IllegalArgumentException ex) {
+ continue; // a malformed escape: the call throws
+ }
+ assertUtilityBounds(utils, call.getKey(), actual, s);
+ }
+ }
+ for (String s : TEXTS) {
+ assertUtilityBounds(utils, "truncateNicely", utils.truncateNicely(s, 1, 2, "..."),
+ s, 1, 2, "...");
+ assertUtilityBounds(utils, "truncateText", utils.truncateText(s, 1, 2, "..."),
+ s, 1, 2, "...");
+ assertUtilityBounds(utils, "truncate", utils.truncate(s, 1, 2, "..."),
+ s, 1, 2, "...");
+ assertUtilityBounds(utils, "left", utils.left(s, 2), s, 2);
+ assertUtilityBounds(utils, "removeHTML", utils.removeHTML(s, false), s, false);
+ }
+ for (int n = 0; n < 10; n++) {
+ byte[] bytes = new byte[n];
+ assertUtilityBounds(utils, "toBase64", utils.toBase64(bytes), bytes, null);
+ }
+ }
+
+ @Test
+ void dateFormatsAreBounded() {
+ Date date = new Date(1_700_000_000_000L);
+ // every pattern letter SimpleDateFormat knows, each at its longest form
+ StringBuilder all = new StringBuilder();
+ for (char c : "GyYMLwWDdFEuaHkKhmsSzZX".toCharArray()) {
+ all.append(String.valueOf(c).repeat(c == 'X' ? 3 : 4)).append(' ');
+ }
+ int checked = 0;
+ for (Locale l : Locale.getAvailableLocales()) {
+ String actual = new java.text.SimpleDateFormat(all.toString(), l).format(date);
+ long bound = StringGrowth.maxResultLength(new UtilitiesModel(), "formatDate",
+ new Object[] {date, all.toString(), null});
+ assertTrue(bound >= actual.length(), l + ": " + actual.length() + " > " + bound);
+ checked++;
+ }
+ assertTrue(checked > 100, "only " + checked + " locales were checked");
+ }
+
+ /** Plain text gives a bound equal to its length, so large plain text still fits. */
+ @Test
+ void utilitiesCallsOnPlainTextAreNotOverestimated() {
+ UtilitiesModel utils = new UtilitiesModel();
+ String plain = "Hello World 0123456789 abc";
+ for (String name : oneStringCalls(utils).keySet()) {
+ if ("hexEncode".equals(name)) {
+ continue; // every character becomes at least three
+ }
+ assertTrue(StringGrowth.maxResultLength(utils, name, new Object[] {plain})
+ <= plain.length(), name);
+ }
+ assertEquals(3 * plain.length(), StringGrowth.maxResultLength(utils, "hexEncode",
+ new Object[] {plain}));
+ // escapeHTML and escapeXML leave most letters outside ASCII alone
+ String text = "\u041f\u0440\u0438\u0432\u0435\u0442 \u4f60\u597d \u3053\u3093\u306b\u3061\u306f";
+ for (String name : new String[] {"escapeHTML", "escapeXML", "transformToHTMLSubset"}) {
+ assertEquals(text.length(), StringGrowth.maxResultLength(utils, name,
+ new Object[] {text}), name);
+ }
+ // a value that isn't a string is counted by its text
+ assertTrue(StringGrowth.maxResultLength(utils, "escapeHTML", new Object[] {12345}) <= 5);
+ assertTrue(StringGrowth.maxResultLength(utils, "escapeHTML",
+ new Object[] {new StringBuilder("<<= "<<<ab".length());
+ }
+
+ /** A String-returning method added to UtilitiesModel is refused until it is bounded here. */
+ @Test
+ void everyUtilitiesStringMethodIsKnown() {
+ UtilitiesModel utils = new UtilitiesModel();
+ for (Method m : UtilitiesModel.class.getMethods()) {
+ if (Modifier.isPublic(m.getModifiers())
+ && CharSequence.class.isAssignableFrom(m.getReturnType())) {
+ assertFalse(StringGrowth.isRefused(utils, m.getName(), m.getReturnType()),
+ m.getName());
+ }
+ }
+ assertTrue(StringGrowth.isRefused(utils, "someNewMethod", String.class));
+ assertFalse(StringGrowth.isRefused(utils, "someNewMethod", boolean.class));
+ }
+
+ @Test
+ void utilitiesReplaceIsExact() {
+ UtilitiesModel utils = new UtilitiesModel();
+ assertEquals(3 + 2 * 3, StringGrowth.maxResultLength(utils, "replace",
+ new Object[] {"a.a", "a", "xyzw"}));
+ assertEquals(3 + 3, StringGrowth.maxResultLength(utils, "replace",
+ new Object[] {"a.a", "a", "xyzw", 1}));
+ assertEquals(0, StringGrowth.maxResultLength(utils, "replace",
+ new Object[] {"a.a", "", "xyzw"}));
+ }
+
+ /** A list appended as an Object is printed in full, so it counts as its text. */
+ @Test
+ void appendingAListCountsItsText() {
+ java.util.List list = new ArrayList<>();
+ for (int i = 0; i < 1000; i++) {
+ list.add(i);
+ }
+ StringBuilder b = new StringBuilder("x");
+ long bound = StringGrowth.maxResultLength(b, "append", new Object[] {list});
+ assertTrue(bound >= 1 + list.toString().length(), "bound was " + bound);
+ assertTrue(StringGrowth.maxResultLength(b, "append", new Object[] {null}) >= 5);
+ }
+
+ @Test
+ void builderGrowthIsBounded() {
+ StringBuilder b = new StringBuilder("abc");
+ assertEquals(3 + 5, StringGrowth.maxResultLength(b, "append", new Object[] {"hello"}));
+ assertEquals(1_000_000_000L, StringGrowth.maxResultLength(b, "setLength",
+ new Object[] {1_000_000_000}));
+ assertTrue(StringGrowth.isRefused(b, "repeat", StringBuilder.class));
+ }
+
+ @Test
+ void hugeBoundsDoNotOverflow() {
+ String s = "0".repeat(100_000);
+ String r = "x".repeat(50_000);
+ long bound = StringGrowth.maxResultLength(s, "replace", new Object[] {"", r});
+ assertTrue(bound > Integer.MAX_VALUE, "bound was " + bound);
+ }
+
+ @Test
+ void unboundableStringMethodsAreRefused() {
+ for (String name : new String[] {"repeat", "format", "formatted", "join", "indent"}) {
+ assertTrue(StringGrowth.isRefused("x", name, String.class), name);
+ }
+ assertTrue(StringGrowth.isRefused("x", "someNewMethod", String.class));
+ for (String name : new String[] {"replace", "substring", "trim", "toUpperCase", "valueOf"}) {
+ assertFalse(StringGrowth.isRefused("x", name, String.class), name);
+ }
+ assertFalse(StringGrowth.isRefused("x", "length", int.class));
+ assertFalse(StringGrowth.isRefused("x", "split", String[].class));
+ }
+}
diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/WeblogTemplateScopeTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/WeblogTemplateScopeTest.java
new file mode 100644
index 0000000000..03b9c9beb2
--- /dev/null
+++ b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/WeblogTemplateScopeTest.java
@@ -0,0 +1,287 @@
+/*
+ * 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.
+ */
+
+package org.apache.roller.weblogger.ui.rendering.velocity;
+
+import java.io.StringWriter;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.roller.weblogger.TestUtils;
+import org.apache.roller.weblogger.business.WeblogManager;
+import org.apache.roller.weblogger.business.WebloggerFactory;
+import org.apache.roller.weblogger.pojos.CustomTemplateRendition;
+import org.apache.roller.weblogger.pojos.TemplateRendition.RenditionType;
+import org.apache.roller.weblogger.pojos.TemplateRendition.TemplateLanguage;
+import org.apache.roller.weblogger.pojos.ThemeTemplate.ComponentType;
+import org.apache.roller.weblogger.pojos.User;
+import org.apache.roller.weblogger.pojos.Weblog;
+import org.apache.roller.weblogger.pojos.WeblogTemplate;
+import org.apache.roller.weblogger.pojos.WeblogTheme;
+import org.apache.roller.weblogger.pojos.wrapper.WeblogWrapper;
+import org.apache.roller.weblogger.ui.rendering.mobile.MobileDeviceRepository.DeviceType;
+import org.apache.velocity.exception.VelocityException;
+import org.apache.velocity.util.ExtProperties;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Renders weblogs' own stored templates through the shipped engine and
+ * VelocityRenderer, as the page servlets do, to check that one weblog's
+ * templates and macros stay its own: another weblog cannot read them with
+ * #include or #parse, or replace them by defining a macro of the same name.
+ */
+public class WeblogTemplateScopeTest {
+
+ private static final Log LOG = LogFactory.getLog(WeblogTemplateScopeTest.class);
+
+ private User userA;
+ private User userB;
+ private Weblog weblogA;
+ private Weblog weblogB;
+
+ /** The page model a weblog template sees, reduced to what these use. */
+ public static class StubModel {
+ private final WeblogWrapper weblog;
+
+ StubModel(Weblog weblog) {
+ this.weblog = WeblogWrapper.wrap(weblog,
+ WebloggerFactory.getWeblogger().getUrlStrategy());
+ }
+
+ public WeblogWrapper getWeblog() {
+ return weblog;
+ }
+
+ public String getDeviceType() {
+ return DeviceType.standard.toString();
+ }
+ }
+
+ @BeforeEach
+ public void setUp() throws Exception {
+ TestUtils.setupWeblogger();
+ RollerVelocityTestSupport.install();
+ try {
+ userA = TestUtils.setupUser("scopeRenderUserA");
+ userB = TestUtils.setupUser("scopeRenderUserB");
+ weblogA = customTheme(TestUtils.setupWeblog("scopeRenderWeblogA", userA));
+ weblogB = customTheme(TestUtils.setupWeblog("scopeRenderWeblogB", userB));
+ TestUtils.endSession(true);
+ } catch (Exception ex) {
+ LOG.error(ex);
+ throw new Exception("Test setup failed", ex);
+ }
+ }
+
+ @AfterEach
+ public void tearDown() throws Exception {
+ try {
+ TestUtils.teardownWeblog(weblogA.getId());
+ TestUtils.teardownWeblog(weblogB.getId());
+ TestUtils.teardownUser(userA.getUserName());
+ TestUtils.teardownUser(userB.getUserName());
+ TestUtils.endSession(true);
+ } catch (Exception ex) {
+ LOG.error(ex);
+ throw new Exception("Test teardown failed", ex);
+ }
+ }
+
+ private static Weblog customTheme(Weblog weblog) throws Exception {
+ weblog.setEditorTheme(WeblogTheme.CUSTOM);
+ WebloggerFactory.getWeblogger().getWeblogManager().saveWeblog(weblog);
+ return weblog;
+ }
+
+ private static String createTemplate(Weblog weblog, String name, String source)
+ throws Exception {
+ WeblogTemplate template = new WeblogTemplate();
+ template.setAction(ComponentType.CUSTOM);
+ template.setName(name);
+ template.setDescription(name);
+ template.setLastModified(new java.util.Date());
+ template.setWeblog(TestUtils.getManagedWebsite(weblog));
+ CustomTemplateRendition rendition =
+ new CustomTemplateRendition(template, RenditionType.STANDARD);
+ rendition.setTemplate(source);
+ rendition.setTemplateLanguage(TemplateLanguage.VELOCITY);
+ WebloggerFactory.getWeblogger().getWeblogManager().saveTemplate(template);
+ TestUtils.endSession(true);
+ return template.getId();
+ }
+
+ private static void editTemplate(String id, String source) throws Exception {
+ WeblogManager mgr = WebloggerFactory.getWeblogger().getWeblogManager();
+ CustomTemplateRendition rendition = mgr.getTemplate(id)
+ .getTemplateRendition(RenditionType.STANDARD);
+ rendition.setTemplate(source);
+ mgr.saveTemplateRendition(rendition);
+ TestUtils.endSession(true);
+ }
+
+ private static String render(Weblog weblog, String templateId) throws Exception {
+ WeblogTemplate template = WebloggerFactory.getWeblogger().getWeblogManager()
+ .getTemplate(templateId);
+ Map model = new HashMap<>();
+ model.put("model", new StubModel(TestUtils.getManagedWebsite(weblog)));
+ StringWriter out = new StringWriter();
+ new VelocityRenderer(template, DeviceType.standard).render(model, out);
+ return out.toString();
+ }
+
+ @Test
+ public void includeCannotReadAnotherWeblogsTemplate() throws Exception {
+ String secret = createTemplate(weblogB, "secret", "B-PRIVATE-SOURCE #set($x = 1)");
+ String page = createTemplate(weblogA, "page", "[#include(\"" + secret + "|standard\")]");
+
+ String output = render(weblogA, page);
+ assertFalse(output.contains("B-PRIVATE-SOURCE"),
+ "#include returned another weblog's template:\n" + output);
+ }
+
+ @Test
+ public void parseCannotRenderAnotherWeblogsTemplate() throws Exception {
+ String secret = createTemplate(weblogB, "secret", "B-PRIVATE-SOURCE");
+ String page = createTemplate(weblogA, "page", "[#parse(\"" + secret + "|standard\")]");
+
+ String output = render(weblogA, page);
+ assertFalse(output.contains("B-PRIVATE-SOURCE"),
+ "#parse rendered another weblog's template:\n" + output);
+ }
+
+ @Test
+ public void aWeblogCanStillIncludeItsOwnTemplates() throws Exception {
+ String part = createTemplate(weblogA, "part", "A-PART");
+ String page = createTemplate(weblogA, "page",
+ "[#include(\"" + part + "|standard\")]"
+ + "[#parse(\"" + part + "|standard\")]"
+ + "[#includeTemplate($model.weblog \"part\")]");
+
+ assertEquals("[A-PART][A-PART][A-PART]", render(weblogA, page).trim());
+ }
+
+ @Test
+ public void errorPageDoesNotShowTemplateIds() throws Exception {
+ String page = createTemplate(weblogA, "broken-page", "#foreach(");
+ String part = createTemplate(weblogA, "broken-part", "#foreach(");
+ String includer = createTemplate(weblogA, "includer",
+ "#includeTemplate($model.weblog \"broken-part\")");
+
+ String output = render(weblogA, page);
+ assertTrue(output.contains("Velocity template error"),
+ "expected the error page:\n" + output);
+ assertFalse(output.contains(page), "the error page showed the template id:\n" + output);
+ assertTrue(output.contains("line 1, column"),
+ "the error page should still say where the error is:\n" + output);
+
+ output = render(weblogA, includer);
+ assertTrue(output.contains("Velocity template error"),
+ "expected the error page:\n" + output);
+ assertFalse(output.contains(includer) || output.contains(part),
+ "the error page showed a template id:\n" + output);
+ }
+
+ @Test
+ public void inlineMacrosBelongToTheWeblogThatDefinesThem() throws Exception {
+ String pageA = createTemplate(weblogA, "page", "#macro(scopeProbe)A-MACRO#end[#scopeProbe()]");
+ String pageB = createTemplate(weblogB, "page", "#macro(scopeProbe)B-MACRO#end[#scopeProbe()]");
+
+ assertEquals("[A-MACRO]", render(weblogA, pageA).trim());
+ assertEquals("[B-MACRO]", render(weblogB, pageB).trim(),
+ "weblog B rendered weblog A's macro");
+ assertEquals("[A-MACRO]", render(weblogA, pageA).trim());
+
+ editTemplate(pageA, "#macro(scopeProbe)A-EDITED#end[#scopeProbe()]");
+ assertEquals("[A-EDITED]", render(weblogA, pageA).trim(),
+ "an edited macro was not picked up");
+ assertEquals("[B-MACRO]", render(weblogB, pageB).trim());
+ }
+
+ @Test
+ public void anInlineMacroDoesNotReplaceALibraryMacroForOtherWeblogs() throws Exception {
+ String pageA = createTemplate(weblogA, "page",
+ "#macro(includeTemplate $weblog $name)A-REPLACED#end"
+ + "[#includeTemplate($model.weblog \"part\")]");
+ createTemplate(weblogB, "part", "B-PART");
+ String pageB = createTemplate(weblogB, "page",
+ "[#includeTemplate($model.weblog \"part\")]");
+
+ assertEquals("[A-REPLACED]", render(weblogA, pageA).trim());
+ assertEquals("[B-PART]", render(weblogB, pageB).trim(),
+ "weblog A's macro replaced the library macro for weblog B");
+ }
+
+ @Test
+ public void macrosStillReachAcrossAWeblogsOwnTemplates() throws Exception {
+ createTemplate(weblogA, "macros", "#macro(fromLibrary)LIB-OF-A#end");
+ createTemplate(weblogA, "child", "[child:#fromParent()]");
+ createTemplate(weblogA, "uses-library", "[sibling:#fromLibrary()]");
+ String defs = createTemplate(weblogA, "defs", "#macro(fromDefs)DEFS-OF-A#end");
+
+ // a macro defined in a template the page includes, through the
+ // library macro themes use and through #parse directly
+ String viaIncludeTemplate = createTemplate(weblogA, "page1",
+ "#includeTemplate($model.weblog \"macros\")[#fromLibrary()]");
+ assertEquals("[LIB-OF-A]", render(weblogA, viaIncludeTemplate).trim());
+
+ String viaParse = createTemplate(weblogA, "page2",
+ "#parse(\"" + defs + "|standard\")[#fromDefs()]");
+ assertEquals("[DEFS-OF-A]", render(weblogA, viaParse).trim());
+
+ // a macro the page defines, called from a template it includes
+ String parentToChild = createTemplate(weblogA, "page3",
+ "#macro(fromParent)PARENT-OF-A#end#includeTemplate($model.weblog \"child\")");
+ assertEquals("[child:PARENT-OF-A]", render(weblogA, parentToChild).trim());
+
+ // a macro one included template defines, called from the next
+ String siblings = createTemplate(weblogA, "page4",
+ "#includeTemplate($model.weblog \"macros\")"
+ + "#includeTemplate($model.weblog \"uses-library\")");
+ assertEquals("[sibling:LIB-OF-A]", render(weblogA, siblings).trim());
+
+ // weblog B does not see any of weblog A's macros
+ String pageB = createTemplate(weblogB, "page", "[#fromLibrary()]");
+ assertEquals("[#fromLibrary()]", render(weblogB, pageB).trim());
+ }
+
+ /**
+ * Velocity's cache would hand a template loaded for one weblog to another
+ * without asking the loader, so the stored template loader won't start
+ * with caching on.
+ */
+ @Test
+ public void theStoredTemplateLoaderDoesNotStartWithCachingOn() {
+ ExtProperties config = new ExtProperties();
+ config.setProperty("cache", "true");
+ assertThrows(VelocityException.class, () -> new RollerResourceLoader().init(config));
+
+ ExtProperties shipped = new ExtProperties();
+ shipped.setProperty("cache", "false");
+ new RollerResourceLoader().init(shipped);
+ }
+}
diff --git a/app/src/test/resources/WEB-INF/velocity.properties b/app/src/test/resources/WEB-INF/velocity.properties
index 4c218366fe..e44d26142a 100644
--- a/app/src/test/resources/WEB-INF/velocity.properties
+++ b/app/src/test/resources/WEB-INF/velocity.properties
@@ -62,15 +62,48 @@ velocimacro.library.autoreload=true
# Allow Velocimacros to be defined in regular templates
velocimacro.inline.allow=true
-# Allow template authors to define macros in any template
-velocimacro.inline.local_scope=false
+# Macros a template defines belong to that template, and to the render it
+# starts, so one weblog's macro never replaces another's of the same name and
+# an edited macro takes effect on the next render. With replace_global, the
+# page's macros are also seen by the templates it #parses, and a macro
+# defined in a #parse'd template is seen by the rest of the page, as before.
+# Library macros (velocimacro.library.path) stay global.
+velocimacro.inline.local_scope=true
+velocimacro.inline.replace_global=true
# set encoding/charset to UTF-8
resource.default_encoding=UTF-8
default.contentType=text/html; charset=utf-8
-# Weblog templates render under SecureUberspector, which governs method access
-# rather than resource resolution, so the include directives are confined
-# separately. Keep this aligned with /WEB-INF/velocity.properties.
-introspector.uberspect.class=org.apache.velocity.util.introspection.SecureUberspector
+# Keep these settings aligned with /WEB-INF/velocity.properties.
+#
+# Weblog templates are written by weblog authors, so a render is bounded by
+# rendering.maxOutputChars and rendering.maxRenderSeconds in
+# roller.properties, and by a budget for the strings and list items it builds
+# in memory (RenderSession). Each setting below does part of that:
+# - parser.class: RenderLimitParser swaps in nodes that stop string literals,
+# + and blocks used as strings at the output limit as they are built, check
+# the text of a list or map before == or != compares it with a string, and
+# check the size of big numbers before * multiplies them.
+# - introspector.uberspect.class: RenderLimitUberspector, chained after
+# SecureUberspector, checks the deadline on every method call and property
+# read, stops a call that returns or could build a string longer than the
+# output limit, a list or map past the budget, or a number too large to
+# work with, and runs regular expressions given to String methods under
+# the deadline. It does not offer the methods whose result can't be bounded
+# from the call: repeat, format, formatted, join, indent, lines and
+# splitWithDelimiters on String, any other String method returning a string
+# that StringGrowth doesn't know, repeat on StringBuilder and StringBuffer,
+# and the methods of a Class object other than getName.
+# - runtime.custom_directives: RollerForeach checks the deadline on every
+# #foreach pass, and fails the render on a loop of more than 100,000 passes.
+# - event_handler.reference_insertion.class: RenderLimitInsertionHandler
+# checks the deadline, and each inserted value against the output limit.
+parser.class=org.apache.roller.weblogger.ui.rendering.velocity.RenderLimitParser
+introspector.uberspect.class=org.apache.velocity.util.introspection.SecureUberspector,org.apache.roller.weblogger.ui.rendering.velocity.RenderLimitUberspector
+runtime.custom_directives=org.apache.roller.weblogger.ui.rendering.velocity.RollerForeach
+event_handler.reference_insertion.class=org.apache.roller.weblogger.ui.rendering.velocity.RenderLimitInsertionHandler
+
+# SecureUberspector governs method access, not resource resolution, so the
+# include directives are confined separately.
event_handler.include.class=org.apache.roller.weblogger.ui.rendering.velocity.ThemeIncludeEventHandler
diff --git a/app/src/test/resources/roller-custom.properties b/app/src/test/resources/roller-custom.properties
index 23a2c28db2..659040ec33 100644
--- a/app/src/test/resources/roller-custom.properties
+++ b/app/src/test/resources/roller-custom.properties
@@ -42,3 +42,6 @@ tasks.TestTask.class=org.apache.roller.weblogger.business.TestTask
tasks.TestTask.startTime=immediate
tasks.TestTask.interval=1800
tasks.TestTask.leaseTime=300
+
+# Keep render-deadline tests short.
+rendering.maxRenderSeconds=5