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

snoopdave pushed a commit to branch roller-6.1.x
in repository https://gitbox.apache.org/repos/asf/roller.git


The following commit(s) were added to refs/heads/roller-6.1.x by this push:
     new 193d70f78 Keep templates and macros per weblog, and bound render 
output and time (#366)
193d70f78 is described below

commit 193d70f7841fc5892ac7e85896abdd47f6c1bf22
Author: David M. Johnson <[email protected]>
AuthorDate: Sat Nov 21 15:30:37 2026 -0500

    Keep templates and macros per weblog, and bound render output and time 
(#366)
    
    * Keep templates and macros per weblog, and bound render output and time
    
    A slimmer version of #335 without the in-memory render budget. #parse and
    #include load only the rendering weblog's own templates, inline macros are
    local to the template that defines them, and a render fails once it writes
    more than rendering.maxOutputChars, runs past rendering.maxRenderSeconds,
    or makes more than 100,000 #foreach passes.
    
    Co-authored-by: Matt Raible <[email protected]>
    
    * Reference #366 in CHANGES
    
    * Add the security model to 6.1.x, and put template resource use out of 
scope
    
    Copies SECURITY.md and docs/security-model.md from #202. A global admin who
    turns on custom themes trusts weblog Admins not to abuse the server's CPU
    and memory; the template sandbox stays a security boundary.
    
    ---------
    
    Co-authored-by: Matt Raible <[email protected]>
---
 CHANGES.md                                         |  21 +-
 SECURITY.md                                        |  50 +++
 .../rendering/velocity/RenderLimitException.java   |  34 ++
 .../velocity/RenderLimitInsertionHandler.java      |  40 +++
 .../ui/rendering/velocity/RenderLimitWriter.java   |  76 +++++
 .../ui/rendering/velocity/RenderSession.java       | 145 ++++++++
 .../ui/rendering/velocity/RollerForeach.java       |  80 +++++
 .../rendering/velocity/RollerResourceLoader.java   |  45 ++-
 .../ui/rendering/velocity/VelocityRenderer.java    | 129 +++++++-
 .../roller/weblogger/config/roller.properties      |   7 +
 app/src/main/webapp/WEB-INF/velocity.properties    |  21 +-
 .../WEB-INF/velocity/templates/error-page.vm       |   6 +-
 .../WEB-INF/velocity/templates/error-parse.vm      |   6 +-
 .../ui/rendering/velocity/RenderLimitsTest.java    | 231 +++++++++++++
 .../velocity/RollerVelocityTestSupport.java        | 196 +++++++++++
 .../velocity/WeblogTemplateScopeTest.java          | 287 ++++++++++++++++
 app/src/test/resources/WEB-INF/velocity.properties |  22 +-
 app/src/test/resources/roller-custom.properties    |   3 +
 docs/security-model.md                             | 368 +++++++++++++++++++++
 19 files changed, 1718 insertions(+), 49 deletions(-)

diff --git a/CHANGES.md b/CHANGES.md
index 2dbf9731d..6da5553f1 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -19,13 +19,20 @@
   `InitFilter.getAbsoluteUrl` are removed (#337).
 
 - **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).
+  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. `#parse` and `#include` load only the weblog's
+  own templates. Error pages no longer show template ids (#366).
+- **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 (#366).
 
 - **Entries with scripts or embeds open as HTML.** If an entry contains
   scripts, frames, embedded objects, event-handler attributes or
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 000000000..165754983
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,50 @@
+<!--
+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
+
+    https://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.
+-->
+
+# Security policy
+
+## Reporting a vulnerability
+
+Report suspected security vulnerabilities in Apache Roller privately to the
+Apache Security Team at [[email protected]](mailto:[email protected]).
+Please do **not** report them in the public issue tracker, in GitHub issues or
+pull requests, or on the public mailing lists.
+
+A useful report says which Roller version you tested, how the site is
+configured in any way that matters to the issue, and what steps reproduce the
+behaviour. If you are not sure whether what you found is a vulnerability,
+report it privately anyway and we will work it out with you.
+
+The Apache Security Team forwards the report to the Roller PMC. See the
+[ASF security page](https://www.apache.org/security/) for the foundation-wide
+process.
+
+## Security model
+
+The [Roller security model](docs/security-model.md) explains who Roller trusts,
+what each kind of user may do, and what counts as a vulnerability. Please read
+it before you report.
+
+## Supported versions
+
+Security fixes are made on the current release line and shipped in a new
+release. Older releases are not patched. If you run an older version, upgrade
+to the [current release](https://roller.apache.org/downloads/downloads.html).
+
+## Advisories
+
+Advisories are listed at <https://roller.apache.org/security.html>.
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.
+ *
+ * <p>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<RenderSession> 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<Object> {
+
+        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 4159c6437..89b3ea8c9 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;
 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 class RollerResourceLoader extends ResourceLoader {
                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 class RollerResourceLoader extends ResourceLoader {
                        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 class RollerResourceLoader extends ResourceLoader {
                        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 class RollerResourceLoader extends ResourceLoader {
                }
        }
 
+       /**
+        * 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 3ea45bab6..744bdc53c 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 @@ package org.apache.roller.weblogger.ui.rendering.velocity;
 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 class VelocityRenderer implements Renderer {
             // 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 class VelocityRenderer implements Renderer {
     public void render(Map<String, Object> 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 class VelocityRenderer implements Renderer {
 
                 // 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 class VelocityRenderer implements Renderer {
                 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 class VelocityRenderer implements Renderer {
 
             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<String, Object> 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 @@ public class VelocityRenderer implements Renderer {
 
             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 ef7f48b47..6d74e41af 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
@@ -505,6 +505,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
+
 #-----------------------------------------------------------------------------
 # Weblog ping system
 #-----------------------------------------------------------------------------
diff --git a/app/src/main/webapp/WEB-INF/velocity.properties 
b/app/src/main/webapp/WEB-INF/velocity.properties
index 190a7bbbc..d3e056707 100644
--- a/app/src/main/webapp/WEB-INF/velocity.properties
+++ b/app/src/main/webapp/WEB-INF/velocity.properties
@@ -62,8 +62,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
@@ -71,6 +77,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 94b84fee9..194bddbad 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 @@
         </tr>
         <tr>
           <td class="dottedtable" width="20%">Message</td>
-          <td 
class="dottedtable">$utils.autoformat($utils.escapeHTML($exception.getMessage()))</td>
-        </tr>
-        <tr>
-          <td class="dottedtable" width="20%">Type</td>
-          <td class="dottedtable">$exceptionSource</td>
+          <td 
class="dottedtable">$utils.autoformat($utils.escapeHTML($exceptionMessage))</td>
         </tr>
         <tr>
           <td class="dottedtable" width="20%">Exception</td>
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 bdb378e8a..fa466cc5a 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 @@
     </tr>
     <tr>
       <td style="border: 1px dotted #CCCCCC;" width="25%">Message</td>
-      <td style="border: 1px dotted 
#CCCCCC;">$utils.autoformat($utils.escapeHTML($exception.getMessage()))</td>
-    </tr>
-    <tr>
-      <td style="border: 1px dotted #CCCCCC;" width="25%">Type</td>
-      <td style="border: 1px dotted #CCCCCC;">$exceptionSource</td>
+      <td style="border: 1px dotted 
#CCCCCC;">$utils.autoformat($utils.escapeHTML($exceptionMessage))</td>
     </tr>
     <tr>
       <td style="border: 1px dotted #CCCCCC;" width="25%">Exception</td>
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..f9e1eaa30
--- /dev/null
+++ 
b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitsTest.java
@@ -0,0 +1,231 @@
+/*
+ * 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.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<String, 
Object> 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("<!-- error-parse -->"),
+                "rendering wrote " + 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("<!-- error-parse -->"),
+                "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..ca2e9606b
--- /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<String, String> 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<String, Object> 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 4c218366f..0aa3c9c38 100644
--- a/app/src/test/resources/WEB-INF/velocity.properties
+++ b/app/src/test/resources/WEB-INF/velocity.properties
@@ -62,8 +62,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
@@ -73,4 +79,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 23a2c28db..659040ec3 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
diff --git a/docs/security-model.md b/docs/security-model.md
new file mode 100644
index 000000000..1c5d3d5a7
--- /dev/null
+++ b/docs/security-model.md
@@ -0,0 +1,368 @@
+<!--
+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
+
+    https://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.
+-->
+
+# Apache Roller security model
+
+## About this document
+
+- **Version**: this model describes the Apache Roller 6.1.x release line.
+- **Purpose**: it tells operators what Roller protects and what it leaves to 
them, and tells security researchers what counts as a vulnerability.
+- **Reporting**: report a suspected vulnerability privately to 
[email protected], as described in [SECURITY.md](../SECURITY.md).
+- **Vulnerabilities**: an issue is a vulnerability when an untrusted user 
crosses one of the boundaries below in a supported configuration.
+- **Questions**: ask about the model on the Roller dev list, but never post 
details of a suspected vulnerability there.
+
+## The one rule
+
+Roller is one server that hosts many weblogs for people who do not
+necessarily trust each other. The whole model follows from one rule:
+
+> **What you may do in one weblog gives you nothing in another weblog, and
+> nothing on the server.**
+
+Only two parties are trusted: the **global admin**, who runs the site, and the
+**operator**, who runs the server. Everyone else is a possible attacker. That
+includes the admin of a weblog.
+
+## Principles
+
+Every change to Roller must keep these rules:
+
+1. Rights in one weblog give nothing in another weblog or on the server.
+2. Weblog admins are untrusted. Only global admins and the operator are
+   trusted.
+3. Every object named in a request is checked against the weblog the action
+   runs on.
+4. Content that users write never runs as script for other users.
+5. Templates run in a sandbox. They cannot call arbitrary Java code or read
+   files outside their theme.
+6. Request data is data. Roller never runs it as code, and it never resolves
+   external entities in XML it receives.
+7. Every state-changing request from a logged-in user needs a one-time token
+   (the *salt*).
+8. Users below global admin cannot make the server fetch a URL of their
+   choice.
+
+## What Roller is made of
+
+```mermaid
+flowchart TB
+  subgraph Public["Public, no login"]
+    PR["Weblog pages, feeds, search"]
+    CM["Comments"]
+  end
+  subgraph Members["Logged-in users"]
+    AU["Authoring UI<br/>(/roller-ui/authoring)"]
+    API["Remote publishing APIs<br/>XML-RPC, AtomPub, OAuth"]
+  end
+  subgraph Admins["Global admins"]
+    AD["Admin UI<br/>(/roller-ui/admin)"]
+    PL["Planet feed aggregator"]
+    PG["Ping targets"]
+  end
+  subgraph Setup["First run only"]
+    IN["Installer + setup token"]
+  end
+  TH["Bundled themes and templates"]
+  DB[("Database, media files,<br/>search index")]
+  PR --> TH
+  PR --> DB
+  CM --> DB
+  AU --> DB
+  API --> DB
+  AD --> DB
+  IN --> DB
+  PL -->|fetches| NET(("Network"))
+  PG -->|pings| NET
+```
+
+Everything in the Roller WAR is in scope, including the bundled themes. Build
+and test tooling (`db-utils/`, `it-selenium/`, `testing/`, `docker/`,
+`assembly-release/`) is not part of the product and is out of scope. The
+Docker files are examples for development, not a supported deployment.
+
+## The users
+
+Roller has two layers of roles:
+
+- **Global roles** apply to the whole site.
+- **Weblog roles** apply to one weblog. A person can hold a different weblog
+  role in each weblog they belong to, or no role at all.
+
+```mermaid
+flowchart TB
+  subgraph Outside["Outside Roller"]
+    OP["Operator<br/>container, database, config, logs<br/>TRUSTED, out of 
scope"]
+  end
+  subgraph Site["Site-wide: global roles"]
+    GA["Global admin<br/>global role 'admin'<br/>TRUSTED"]
+    RU["Registered user<br/>global role 'editor'<br/>UNTRUSTED"]
+    AN["Anonymous visitor<br/>no account<br/>UNTRUSTED"]
+  end
+  subgraph Weblog["Inside one weblog: weblog roles"]
+    WA["Admin<br/>permission 'admin'<br/>UNTRUSTED"]
+    AU["Author<br/>permission 'post'"]
+    LI["Limited<br/>permission 'edit_draft'"]
+  end
+  OP -->|creates first admin at setup| GA
+  AN -->|registers, if allowed| RU
+  RU -->|creates a weblog| WA
+  RU -->|is invited to a weblog| AU
+  RU -->|is invited to a weblog| LI
+  GA -.->|holds every weblog role<br/>in every weblog| WA
+```
+
+Weblog roles stack: an Admin can do everything an Author can, and an Author can
+do everything a Limited member can.
+
+| User | Can do | Cannot do | Trusted? |
+| --- | --- | --- | --- |
+| **Anonymous visitor** | Read published entries, feeds and search; post 
comments; register, when registration is on | See drafts, settings or anything 
unpublished; change anything | No |
+| **Registered user** (global `editor`) | Log in; edit own profile; comment; 
create weblogs, when the site allows it | Act in a weblog where they hold no 
role | No |
+| **Limited** (`edit_draft`) | Create and edit draft entries in that weblog | 
Publish; manage comments, categories or media; act in other weblogs | No |
+| **Author** (`post`) | Everything Limited can do; publish entries; manage 
comments and categories; manage media, when uploads are on | Change weblog 
settings, members, bookmarks, pings or design | No |
+| **Admin** (`admin`) | Everything Author can do; weblog settings, members, 
bookmarks (including OPML import), pings, maintenance; theme and templates, 
when custom themes are on | Touch other weblogs; read server files; run Java 
code; read other users' private data; run script in other users' browsers | 
**No** |
+| **Global admin** (global `admin`) | Everything in every weblog; users; site 
settings; Planet feeds; ping targets | Get shell or file access on the host | 
Yes |
+| **Network attacker** | Read or change traffic when the site runs over plain 
HTTP | Anything, once the site runs over HTTPS | No |
+| **Operator** | Owns the container, JVM, database, configuration files and 
logs | — | Yes, out of scope |
+
+### Why the weblog Admin is untrusted
+
+This is the most important line in the model. On a multi-user site, anyone who
+can register can create a weblog and become its Admin. If weblog Admins were
+trusted, every registered user would be trusted.
+
+Roller's defaults reflect this. `weblogAdminsUntrusted=true` turns on HTML
+sanitizing, and templates run in a sandbox built for untrusted authors.
+
+A request forged cross-site that makes a logged-in user's browser act is an
+attack by an anonymous visitor, not by that user.
+
+## Where untrusted data enters
+
+| Input | Who controls it |
+| --- | --- |
+| Any request to public pages, feeds and search | Anyone |
+| Comments: name, email, URL, text | Anyone |
+| Entry text, titles and summaries | Weblog members |
+| Categories, bookmarks, profiles, weblog settings | Weblog members and Admins 
|
+| Templates and stylesheets | Weblog Admins, when custom themes are on |
+| Uploaded files: content, name, declared type | Weblog members, when uploads 
are on |
+| OPML bookmark import | Weblog Admins |
+| Remote API requests (XML-RPC, AtomPub, OAuth) | Anyone, before 
authentication |
+| Feeds fetched by Planet | Whoever runs the feed's host |
+| Responses from ping targets | Whoever runs the ping target |
+| Installer forms | Anyone, until setup is complete |
+
+Only the operator controls `roller-custom.properties`, JNDI resources and the
+database.
+
+## The four boundaries
+
+```mermaid
+flowchart LR
+  V["Visitor / commenter"] -->|"① request data"| R["Public 
pages,<br/>comments, search"]
+  M["Member of weblog A"] -->|"② allowed"| A[("Weblog A")]
+  M -. "② blocked" .-> B[("Weblog B")]
+  WA["Weblog Admin"] -->|"③ HTML, templates, uploads"| 
S["Sanitizer,<br/>sandbox,<br/>media policy"]
+  S --> P["Pages that every<br/>visitor's browser runs"]
+  U["Any user below<br/>global admin"] -. "④ blocked" .-> N(("Network"))
+  GA["Global admin"] -->|"④ allowed"| N
+```
+
+1. **Visitor → server.** All request data is untrusted. Roller escapes what it
+   writes back into pages, never runs request data as code, and reads XML as
+   data only. One request that causes runaway CPU or memory use (for example
+   catastrophic regex backtracking) is a vulnerability. A slow response is not.
+2. **Weblog → weblog.** A role in weblog A gives nothing in weblog B. This
+   includes every object named by id in a request: entries, comments, media,
+   templates, categories, bookmarks and members. A global admin holds every 
role
+   in every weblog.
+3. **Weblog author → everyone else.** Content that members and Admins write
+   runs in other people's browsers. Roller keeps it from attacking visitors,
+   other users or the server:
+   - HTML in entries, profiles and settings is sanitized when
+     `weblogAdminsUntrusted=true`.
+   - Comments are always escaped, or limited to a small HTML subset. Comment
+     links and author URLs must be `http` or `https`.
+   - Templates run in the sandbox.
+   - Uploaded files are never served as active content (see below).
+4. **Server → network.** Users below global admin cannot make the server fetch
+   a URL of their choice. Entry enclosure URLs are stored, not fetched. Global
+   admins can point the server at any URL through Planet feeds and ping 
targets.
+   That is by design.
+
+Two more rules protect the whole site:
+
+- **Accounts.** Passwords are stored as bcrypt hashes. Roller takes the user's
+  identity from the login, never from request data. A password change ends the
+  user's other sessions.
+- **Setup.** Before setup, the installer needs a one-time token that Roller
+  writes to the server log. Once setup is complete, the installer is closed for
+  good.
+
+## How a request is checked
+
+Every request to the authoring UI passes these checks in order. A missing check
+creates a predictable class of bug.
+
+```mermaid
+flowchart TD
+  Q["Request to /roller-ui/authoring/..."] --> G1{"Logged in with a global 
role?"}
+  G1 -- no --> X1["Redirect to login"]
+  G1 -- yes --> G2{"Holds the required role<br/>in THIS weblog?"}
+  G2 -- no --> X2["Denied<br/>(missing: privilege escalation)"]
+  G2 -- yes --> G3{"Does every object named<br/>in the request belong<br/>to 
this weblog?"}
+  G3 -- no --> X3["Denied<br/>(missing: cross-weblog access)"]
+  G3 -- yes --> G4{"Valid one-time salt<br/>on a state change?"}
+  G4 -- no --> X4["Rejected<br/>(missing: CSRF)"]
+  G4 -- yes --> OK["Action runs"]
+```
+
+The remote APIs (XML-RPC, AtomPub) authenticate with a username and password,
+or OAuth, instead of a session and salt. They apply the same role and object
+checks.
+
+## How content is kept safe
+
+```mermaid
+flowchart LR
+  subgraph In["Written by untrusted users"]
+    E["Entry HTML,<br/>profiles, settings"]
+    C["Comments"]
+    T["Templates"]
+    U["Uploads"]
+  end
+  E --> SAN["HTML sanitizer<br/>(weblogAdminsUntrusted=true)"]
+  C --> ESC["Escaped, or HTML subset;<br/>links http/https only"]
+  T --> SB["Velocity sandbox:<br/>no arbitrary Java calls,<br/>no reads 
outside the theme"]
+  U --> MT["Type taken from file name;<br/>active types never 
inline;<br/>nosniff"]
+  SAN --> OUT["Page sent to visitors"]
+  ESC --> OUT
+  SB --> OUT
+  MT --> OUT
+```
+
+Uploaded files get their type from the file name, not from what the browser
+claims. Only passive types such as images, audio, video, PDF and plain text are
+shown inline. Everything else, including HTML and SVG, is sent as a download.
+
+## Settings
+
+```mermaid
+flowchart LR
+  subgraph Supported["Optional features: supported when enabled"]
+    S1["XML-RPC"]
+    S2["AtomPub"]
+    S3["Uploads"]
+    S4["Custom themes"]
+    S5["Self-registration"]
+    S6["HTML comments"]
+    S7["LDAP / OpenID login"]
+    S8["Remember-me"]
+    S9["Planet aggregator"]
+  end
+  subgraph Unsupported["Unsupported on a multi-user site"]
+    U1["weblogAdminsUntrusted=false"]
+    U2["authentication.method=cma"]
+    U3["passwds.encryption.enabled=false"]
+  end
+```
+
+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, 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. |
+| `users.comments.htmlenabled` | Allows a small HTML subset in comments. |
+| `authentication.method` | `db`, `ldap`, `openid` or `db-openid`. `cma` is 
not usable. |
+| `rememberme.enabled` | Keeps users logged in with a cookie. Use only over 
HTTPS. |
+| `passwds.encryption.enabled` | `false` stores plaintext passwords. Not 
supported. |
+
+## Libraries
+
+Roller decides how it configures and calls each library. A library bug hit
+while Roller uses the library correctly belongs to that library's project. 
Roller
+passing untrusted input to a library in an unsafe way is a Roller bug.
+
+## Not vulnerabilities
+
+Roller does not protect against:
+
+- **The operator or host**, or anyone who can edit the configuration or the
+  database.
+- **A global admin misusing the admin UI.** A request forged against a 
logged-in
+  global admin is still a vulnerability.
+- **Plain HTTP.** TLS is the operator's job.
+- **Floods, brute-force login attempts and spam.** Roller has no rate limit or
+  login lockout. The comment math question is an anti-spam measure, not
+  authentication.
+- **Browsers out of vendor support.** Script that runs only in such browsers
+  (for example old Internet Explorer modes) is not a vulnerability. A payload
+  that also runs in a current browser is.
+- **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.
+
+## Operator checklist
+
+- Serve Roller only over HTTPS, and set the session cookie `Secure` flag in the
+  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.
+- If the server can reach internal services, put egress rules on Roller's
+  outbound traffic (Planet, pings).
+- Run the current release. Older releases are not patched.
+
+## Common mistakes
+
+- Setting `weblogAdminsUntrusted=false` on a multi-user site to allow rich 
HTML.
+- 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.
+
+## Judging a report
+
+```mermaid
+flowchart TD
+  A["Report"] --> B{"Who is the attacker?<br/>(see The users)"}
+  B -- "Operator, or a global admin<br/>acting directly" --> OUT1["Not a 
vulnerability"]
+  B -- "Anyone else, or a request<br/>forged against an admin" --> C{"Does it 
need an<br/>unsupported setting?"}
+  C -- yes --> OUT2["Not a vulnerability"]
+  C -- no --> D{"Does it cross one of<br/>the four boundaries?"}
+  D -- yes --> VALID["Vulnerability"]
+  D -- no --> E{"Listed under<br/>Not vulnerabilities?"}
+  E -- yes --> BD["Not a vulnerability"]
+  E -- no --> GAP["Unclear: the PMC decides<br/>and updates this model"]
+```

Reply via email to