diff --git a/CHANGES.md b/CHANGES.md
index b2240dc96..a7215037f 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -178,14 +178,16 @@
### Behaviour changes worth reading before upgrading
- **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, so weblogs can't affect each other's macros.
- Library macros such as `roller.vm` and a site's own `roller-custom.vm` stay
- global. Error pages no longer show template ids (#317).
+ logged error, once it writes more than `rendering.maxOutputChars` (10 MB),
+ inserts a longer string, or runs longer than `rendering.maxRenderSeconds`
+ (30 seconds), and the page isn't cached. A `#foreach` of more than 100,000
+ passes fails the same way. Templates can no longer call
+ `$utils.addNofollow`, a breaking change. `#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, so weblogs
+ can't affect each other's macros. Library macros such as `roller.vm` and a
+ site's own `roller-custom.vm` stay global. Error pages no longer show
+ template ids (#317).
- **Entries with scripts or embeds open as HTML.** If an entry contains
scripts, frames, embedded objects, event-handler attributes or
`javascript:` links, the rich-text editor opens it in the HTML textarea
diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/model/UtilitiesModel.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/model/UtilitiesModel.java
index a07e858bc..4e396a629 100644
--- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/model/UtilitiesModel.java
+++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/model/UtilitiesModel.java
@@ -366,13 +366,6 @@ public final String decode(String s) {
}
}
- /**
- * Code (stolen from Pebble) to add rel="nofollow" string to all links in HTML.
- */
- public String addNofollow(String html) {
- return Utilities.addNofollow(html);
- }
-
/**
* Transforms the given String into a subset of HTML displayable on a web
* page. The subset includes <b>, <i>, <p>, <br>,
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 000000000..06d6ff4a2
--- /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 000000000..55f2b9316
--- /dev/null
+++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitInsertionHandler.java
@@ -0,0 +1,40 @@
+/*
+ * 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();
+ if (value instanceof CharSequence) {
+ RenderSession.checkLength(((CharSequence) value).length());
+ }
+ return value;
+ }
+}
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 000000000..812a4281b
--- /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 000000000..f5e999210
--- /dev/null
+++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderSession.java
@@ -0,0 +1,145 @@
+/*
+ * 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 and reference
+ * insertion) check the current session rather than trusting the
+ * template. Outside a session those hooks apply no limits. A session started
+ * inside another one shares that one's limits and deadline.
+ */
+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;
+
+ private static final ThreadLocal CURRENT = new ThreadLocal<>();
+
+ private final String weblogId;
+ private final Limits limits;
+ private final RenderSession previous;
+
+ /** The limits of one render, shared by the sessions started inside it. */
+ private static final class Limits {
+ final long maxOutputChars;
+ final int maxRenderSeconds;
+ final long deadline;
+
+ Limits() {
+ int chars = intProperty(MAX_OUTPUT_CHARS, DEFAULT_MAX_OUTPUT_CHARS);
+ maxOutputChars = chars > 0 ? chars : 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.limits = previous != null ? previous.limits : new Limits();
+ }
+
+ /** @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 limits.maxOutputChars;
+ }
+
+ /** Throws once the current render has used up its time. */
+ static void checkDeadline() {
+ RenderSession session = CURRENT.get();
+ if (session != null && session.limits.maxRenderSeconds > 0
+ && System.nanoTime() - session.limits.deadline > 0) {
+ throw new RenderLimitException("rendering took longer than "
+ + session.limits.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.limits.maxOutputChars) {
+ throw new RenderLimitException("a string would be longer than "
+ + session.limits.maxOutputChars + " characters");
+ }
+ }
+}
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 000000000..b5cce131f
--- /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 184ad8f22..5e4b82135 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
@@ -18,10 +18,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;
@@ -31,6 +29,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;
@@ -54,6 +53,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");
+ }
}
/**
@@ -88,7 +92,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");
}
@@ -101,13 +105,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: "
@@ -117,6 +116,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/VelocityRenderer.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/VelocityRenderer.java
index 08c629c92..9fad7dd79 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
@@ -22,14 +22,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;
@@ -43,6 +50,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;
@@ -80,6 +91,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);
@@ -103,16 +116,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();
@@ -128,7 +144,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());
@@ -136,12 +152,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();
@@ -149,20 +165,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;
}
/**
@@ -191,7 +286,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 970dac6f4..1ebcf63fe 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
@@ -518,6 +518,13 @@ 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 inserts 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. Zero means no limit.
+rendering.maxOutputChars=10485760
+rendering.maxRenderSeconds=30
+
#-----------------------------------------------------------------------------
# Pluggable backend, page and editor plugins
#-----------------------------------------------------------------------------
diff --git a/app/src/main/webapp/WEB-INF/velocity.properties b/app/src/main/webapp/WEB-INF/velocity.properties
index c70b5d9ff..fe6d060ea 100644
--- a/app/src/main/webapp/WEB-INF/velocity.properties
+++ b/app/src/main/webapp/WEB-INF/velocity.properties
@@ -63,8 +63,14 @@ 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
@@ -72,6 +78,17 @@ 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 (RenderSession):
+# - 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.
+# VelocityRenderer also checks the output limit and the deadline on every write.
+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/main/webapp/WEB-INF/velocity/templates/error-page.vm b/app/src/main/webapp/WEB-INF/velocity/templates/error-page.vm
index 3a7823f8a..3e6b789b5 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
@@ -70,11 +70,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 5268ab4ab..f183a085e 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
@@ -35,11 +35,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/RenderLimitsTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitsTest.java
new file mode 100644
index 000000000..5698cefd2
--- /dev/null
+++ b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitsTest.java
@@ -0,0 +1,243 @@
+/*
+ * 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.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.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());
+ }
+
+ 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());
+ });
+ }
+
+ /** 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";
+
+ @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());
+ }
+
+ @Test
+ public void utilitiesAddNofollowIsNotAvailable() throws Exception {
+ Map context = new HashMap<>();
+ context.put("utils", new UtilitiesModel());
+ Outcome outcome = render("limits-add-nofollow.vm",
+ "#set($s = 'x ')[$utils.addNofollow($s)]",
+ context);
+ assertEquals(null, outcome.failure);
+ assertEquals("[$utils.addNofollow($s)]", outcome.out.getHead());
+ }
+
+ /** 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();
+ }
+ }
+ }
+ }
+}
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 000000000..d1487bbb1
--- /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 jakarta.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/WeblogTemplateScopeTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/WeblogTemplateScopeTest.java
new file mode 100644
index 000000000..03b9c9beb
--- /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 aa1e34b26..370f0c180 100644
--- a/app/src/test/resources/WEB-INF/velocity.properties
+++ b/app/src/test/resources/WEB-INF/velocity.properties
@@ -63,8 +63,14 @@ 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
@@ -74,4 +80,16 @@ default.contentType=text/html; charset=utf-8
# 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
+
+# Weblog templates are written by weblog authors, so a render is bounded by
+# rendering.maxOutputChars and rendering.maxRenderSeconds in
+# roller.properties (RenderSession):
+# - 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.
+# VelocityRenderer also checks the output limit and the deadline on every write.
+runtime.custom_directives=org.apache.roller.weblogger.ui.rendering.velocity.RollerForeach
+event_handler.reference_insertion.class=org.apache.roller.weblogger.ui.rendering.velocity.RenderLimitInsertionHandler
+
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 61d53dc62..c652cddf1 100644
--- a/app/src/test/resources/roller-custom.properties
+++ b/app/src/test/resources/roller-custom.properties
@@ -64,3 +64,6 @@ tasks.TestTask.leaseTime=300
# tests exercise the provisioning path; the shipped default is false
users.oidc.autoProvision.enabled=true
+
+# Keep render-deadline tests short.
+rendering.maxRenderSeconds=5
diff --git a/docs/roller-template-guide.adoc b/docs/roller-template-guide.adoc
index 4caeeeb24..4a1d7ee7c 100644
--- a/docs/roller-template-guide.adoc
+++ b/docs/roller-template-guide.adoc
@@ -854,8 +854,6 @@ Here’s a comprehensive list of the $utils methods:
* **User getAuthenticatedUser() **Get the current user, or null if no
use is logged in.
-* *String addNowFollow(String s)* Adds the nofollow attribute to any
-HTML links found within the string.
* *String autoformat(String s)* Converts any line-breaks in the string
with* * tags.
* *String decode(String s)* Decodes a string that has been URL encoded.
diff --git a/docs/security-model.md b/docs/security-model.md
index 35915ddae..accbb118b 100644
--- a/docs/security-model.md
+++ b/docs/security-model.md
@@ -284,7 +284,7 @@ A bug in an optional feature is a vulnerability when the feature is enabled.
| Setting | What it changes |
| --- | --- |
| `weblogAdminsUntrusted` | `true` (default) sanitizes HTML from weblog members. Set `false` only when every weblog admin is trusted, such as on a solo blog. |
-| `themes.customtheme.allowed` | Lets weblog Admins edit templates. Templates stay in the sandbox. |
+| `themes.customtheme.allowed` | Lets weblog Admins edit templates. Templates stay in the sandbox, but can use a lot of CPU and memory (see Not vulnerabilities). |
| `uploads.enabled` | Lets members upload media files. |
| `webservices.enableXmlRpc`, `webservices.enableAtomPub` | Turn on the remote publishing APIs. They use the same weblog roles as the UI. |
| `users.registration.enabled` | Lets anyone create an account. |
@@ -317,6 +317,12 @@ Roller does not protect against:
- **Forged anonymous comments.** A comment forged cross-site carries no
identity, so it gains the attacker nothing.
- **Unsupported settings**, listed under Settings above.
+- **Resource use by templates.** When custom themes are on, a weblog Admin's
+ template can use a lot of CPU or memory. Roller bounds a render's output
+ size, time and loop length, but does not promise to stop every expensive
+ template. A global admin who turns custom themes on trusts weblog Admins
+ not to abuse the server's resources. Templates still cannot run Java code,
+ read files outside their theme, or reach other weblogs.
- **Partial writes** when a multi-step operation fails. That is a bug, not a
vulnerability.
@@ -326,6 +332,8 @@ Roller does not protect against:
servlet container. Roller sets `HttpOnly` but not `Secure`.
- Keep `weblogAdminsUntrusted=true` unless every weblog admin is trusted.
- Enable custom themes, uploads, XML-RPC and AtomPub only when you need them.
+ Enable custom themes only for weblog Admins you trust with the server's
+ resources.
- Restrict access to the server log. It holds the setup token during
installation and upgrades.
- Keep the database, data directories and `roller-custom.properties` private.
@@ -336,8 +344,8 @@ Roller does not protect against:
## Common mistakes
- Setting `weblogAdminsUntrusted=false` on a multi-user site to allow rich HTML.
-- Enabling custom themes and assuming templates are harmless. They are
- sandboxed, but they run on every page view.
+- Enabling custom themes on a site where anyone can register. Templates are
+ sandboxed, but one template can still overload the server.
- Running over plain HTTP with remember-me enabled.
- Running setup on a host where other people can read the log.