From 86f204f6ab817259273db0b9ba3c90609792b6cd Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Tue, 17 Nov 2026 16:56:12 -0700 Subject: [PATCH 01/18] Bound weblog template rendering and keep templates and macros per weblog A render now stops with a logged error, and the request fails as for other rendering errors, once it writes more than rendering.maxOutputChars characters (10 MB by default) or runs longer than rendering.maxRenderSeconds (30 by default). The output writer, #foreach, method calls, iteration and every inserted value check these limits, so loops that write nothing and strings built up in memory stop as well. #foreach also stops after 100,000 passes, and String.repeat is not offered to templates. While a weblog is rendered, #parse and #include load only that weblog's own stored templates. The public error pages no longer show template ids; they stay in the log, and the message names the template instead. Macros defined inline in a template are now local to that template and the render it starts, so two weblogs can define macros of the same name and an edited macro takes effect on the next render. Library macros stay global, and macros still reach between a page and the templates it includes. --- .../velocity/RenderLimitException.java | 34 +++ .../velocity/RenderLimitInsertionHandler.java | 40 +++ .../velocity/RenderLimitUberspector.java | 132 +++++++++ .../rendering/velocity/RenderLimitWriter.java | 76 +++++ .../ui/rendering/velocity/RenderSession.java | 119 ++++++++ .../ui/rendering/velocity/RollerForeach.java | 42 +++ .../velocity/RollerResourceLoader.java | 25 +- .../rendering/velocity/VelocityRenderer.java | 111 ++++++-- .../roller/weblogger/config/roller.properties | 6 + .../main/webapp/WEB-INF/velocity.properties | 22 +- .../WEB-INF/velocity/templates/error-page.vm | 6 +- .../WEB-INF/velocity/templates/error-parse.vm | 6 +- .../rendering/velocity/RenderLimitsTest.java | 165 +++++++++++ .../velocity/RollerVelocityTestSupport.java | 173 +++++++++++ .../velocity/WeblogTemplateScopeTest.java | 268 ++++++++++++++++++ .../resources/WEB-INF/velocity.properties | 22 +- .../test/resources/roller-custom.properties | 3 + 17 files changed, 1216 insertions(+), 34 deletions(-) create mode 100644 app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitException.java create mode 100644 app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitInsertionHandler.java create mode 100644 app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitUberspector.java create mode 100644 app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitWriter.java create mode 100644 app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderSession.java create mode 100644 app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerForeach.java create mode 100644 app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitsTest.java create mode 100644 app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerVelocityTestSupport.java create mode 100644 app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/WeblogTemplateScopeTest.java diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitException.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitException.java new file mode 100644 index 0000000000..06d6ff4a2c --- /dev/null +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitException.java @@ -0,0 +1,34 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.roller.weblogger.ui.rendering.velocity; + +/** + * Raised when a template goes past the size or time Roller allows for one + * render. It is unchecked so it passes through Velocity's directives and + * introspection unchanged; VelocityRenderer turns it into a failed render. + */ +public class RenderLimitException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public RenderLimitException(String message) { + super(message); + } +} diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitInsertionHandler.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitInsertionHandler.java new file mode 100644 index 0000000000..55f2b93166 --- /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/RenderLimitUberspector.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitUberspector.java new file mode 100644 index 0000000000..5925f4c75f --- /dev/null +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitUberspector.java @@ -0,0 +1,132 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.roller.weblogger.ui.rendering.velocity; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Iterator; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.velocity.util.introspection.AbstractChainableUberspector; +import org.apache.velocity.util.introspection.Info; +import org.apache.velocity.util.introspection.VelMethod; +import org.apache.velocity.util.introspection.VelPropertyGet; + +/** + * Chained after SecureUberspector, this keeps method calls from templates + * inside the render limits: each call and property read checks the deadline, + * a string a call returns may be no longer than the output limit, and + * String.repeat, which can build a huge string in one call, is not offered. + */ +public class RenderLimitUberspector extends AbstractChainableUberspector { + + private static final Log LOG = LogFactory.getLog(RenderLimitUberspector.class); + + @Override + public Iterator getIterator(Object obj, Info i) { + RenderSession.checkDeadline(); + return super.getIterator(obj, i); + } + + @Override + public VelMethod getMethod(Object obj, String methodName, Object[] args, Info i) { + if (obj instanceof String && "repeat".equals(methodName)) { + LOG.debug("Refusing String.repeat at " + i); + return null; + } + VelMethod method = super.getMethod(obj, methodName, args, i); + return method == null ? null : new LimitedMethod(method); + } + + @Override + public VelPropertyGet getPropertyGet(Object obj, String identifier, Info i) { + VelPropertyGet getter = super.getPropertyGet(obj, identifier, i); + return getter == null ? null : new LimitedPropertyGet(getter); + } + + private static Object checked(Object result) { + if (result instanceof CharSequence) { + RenderSession.checkLength(((CharSequence) result).length()); + } + return result; + } + + private static final class LimitedMethod implements VelMethod { + + private final VelMethod method; + + LimitedMethod(VelMethod method) { + this.method = method; + } + + @Override + public Object invoke(Object o, Object[] params) + throws IllegalAccessException, InvocationTargetException { + RenderSession.checkDeadline(); + return checked(method.invoke(o, params)); + } + + @Override + public boolean isCacheable() { + return method.isCacheable(); + } + + @Override + public String getMethodName() { + return method.getMethodName(); + } + + @Override + public Method getMethod() { + return method.getMethod(); + } + + @Override + public Class getReturnType() { + return method.getReturnType(); + } + } + + private static final class LimitedPropertyGet implements VelPropertyGet { + + private final VelPropertyGet getter; + + LimitedPropertyGet(VelPropertyGet getter) { + this.getter = getter; + } + + @Override + public Object invoke(Object o) throws Exception { + RenderSession.checkDeadline(); + return checked(getter.invoke(o)); + } + + @Override + public boolean isCacheable() { + return getter.isCacheable(); + } + + @Override + public String getMethodName() { + return getter.getMethodName(); + } + } +} diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitWriter.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitWriter.java new file mode 100644 index 0000000000..812a4281b1 --- /dev/null +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitWriter.java @@ -0,0 +1,76 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.roller.weblogger.ui.rendering.velocity; + +import java.io.IOException; +import java.io.Writer; + +/** + * Passes rendered output through, failing the render once it has written more + * than the session allows or run past its deadline. + */ +class RenderLimitWriter extends Writer { + + private final Writer out; + private final long maxChars; + private long written = 0; + + RenderLimitWriter(Writer out, RenderSession session) { + this.out = out; + this.maxChars = session.getMaxOutputChars(); + } + + private void count(long len) { + written += len; + if (written > maxChars) { + throw new RenderLimitException("rendering produced more than " + + maxChars + " characters"); + } + RenderSession.checkDeadline(); + } + + @Override + public void write(int c) throws IOException { + count(1); + out.write(c); + } + + @Override + public void write(char[] cbuf, int off, int len) throws IOException { + count(len); + out.write(cbuf, off, len); + } + + @Override + public void write(String str, int off, int len) throws IOException { + count(len); + out.write(str, off, len); + } + + @Override + public void flush() throws IOException { + out.flush(); + } + + @Override + public void close() throws IOException { + out.close(); + } +} diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderSession.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderSession.java new file mode 100644 index 0000000000..a0dc00dae7 --- /dev/null +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderSession.java @@ -0,0 +1,119 @@ +/* + * 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.roller.weblogger.config.WebloggerConfig; + +/** + * What applies while one template is rendered on this thread: the weblog whose + * stored templates it may load, and how much output and time it may use. + * + *

Weblog templates are written by weblog authors, so the engine's hooks + * (the resource loader, the output writer, #foreach, introspection and + * reference insertion) check the current session rather than trusting the + * template. Outside a session those hooks apply no limits. + */ +final class RenderSession { + + /** Most characters one render may write, or put in one string. */ + static final String MAX_OUTPUT_CHARS = "rendering.maxOutputChars"; + + /** Most seconds one render may take. */ + static final String MAX_RENDER_SECONDS = "rendering.maxRenderSeconds"; + + private static final int DEFAULT_MAX_OUTPUT_CHARS = 10 * 1024 * 1024; + private static final int DEFAULT_MAX_RENDER_SECONDS = 30; + + private static final ThreadLocal CURRENT = new ThreadLocal<>(); + + private final String weblogId; + private final long maxOutputChars; + private final int maxRenderSeconds; + private final long deadline; + private final RenderSession previous; + + private RenderSession(String weblogId, RenderSession previous) { + this.weblogId = weblogId; + this.previous = previous; + int chars = WebloggerConfig.getIntProperty(MAX_OUTPUT_CHARS, + DEFAULT_MAX_OUTPUT_CHARS); + this.maxOutputChars = chars > 0 ? chars : Long.MAX_VALUE; + this.maxRenderSeconds = WebloggerConfig.getIntProperty(MAX_RENDER_SECONDS, + DEFAULT_MAX_RENDER_SECONDS); + this.deadline = maxRenderSeconds > 0 + ? System.nanoTime() + TimeUnit.SECONDS.toNanos(maxRenderSeconds) + : 0; + } + + /** + * 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 maxOutputChars; + } + + /** Throws once the current render has used up its time. */ + static void checkDeadline() { + RenderSession session = CURRENT.get(); + if (session != null && session.maxRenderSeconds > 0 + && System.nanoTime() - session.deadline > 0) { + throw new RenderLimitException("rendering took longer than " + + session.maxRenderSeconds + " seconds"); + } + } + + /** Throws if a value is longer than one render may write. */ + static void checkLength(long length) { + RenderSession session = CURRENT.get(); + if (session != null && length > session.maxOutputChars) { + throw new RenderLimitException("rendering produced more than " + + session.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 0000000000..931f71193c --- /dev/null +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerForeach.java @@ -0,0 +1,42 @@ +/* + * 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 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. Registered in velocity.properties under + * runtime.custom_directives, where it replaces the built-in directive. + */ +public class RollerForeach extends Foreach { + + @Override + protected void renderBlock(InternalContextAdapter context, Writer writer, Node block) + throws IOException { + RenderSession.checkDeadline(); + super.renderBlock(context, writer, block); + } +} diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerResourceLoader.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerResourceLoader.java index 4159c6437b..9b25857b33 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 @@ -87,7 +87,7 @@ public Reader getResourceReader(String name, String encoding) { WeblogTemplate page = WebloggerFactory.getWeblogger() .getWeblogManager().getTemplate(name); - if (page == null) { + if (page == null || !inRenderScope(page)) { throw new ResourceNotFoundException( "RollerResourceLoader: page \"" + name + "\" not found"); } @@ -116,6 +116,29 @@ public Reader getResourceReader(String name, String encoding) { } } + /** + * While a template is being rendered, the only stored templates it may + * load (by #parse or #include) are those of the weblog being rendered, so + * one weblog cannot read or run another's templates by id. Outside + * rendering, the template being loaded is the one the servlet chose. This + * relies on resource.loader.roller.cache=false in velocity.properties, so + * every load comes through here rather than from Velocity's cache. + */ + 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 3ea45bab61..c0686578ed 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/VelocityRenderer.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/VelocityRenderer.java @@ -21,14 +21,21 @@ import java.io.StringWriter; import java.io.Writer; import java.util.Map; +import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.roller.util.RollerConstants; import org.apache.roller.weblogger.pojos.Template; +import org.apache.roller.weblogger.pojos.Weblog; +import org.apache.roller.weblogger.pojos.WeblogTemplate; +import org.apache.roller.weblogger.pojos.wrapper.WeblogWrapper; import org.apache.roller.weblogger.ui.rendering.Renderer; import org.apache.roller.weblogger.ui.rendering.RenderingException; import org.apache.roller.weblogger.ui.rendering.mobile.MobileDeviceRepository; +import org.apache.roller.weblogger.ui.rendering.model.FeedModel; +import org.apache.roller.weblogger.ui.rendering.model.PageModel; +import org.apache.roller.weblogger.ui.rendering.model.SearchResultsFeedModel; import org.apache.roller.weblogger.ui.rendering.model.UtilitiesModel; import org.apache.velocity.VelocityContext; import org.apache.velocity.context.Context; @@ -42,6 +49,10 @@ public class VelocityRenderer implements Renderer { private static final Log log = LogFactory.getLog(VelocityRenderer.class); + // ids Roller gives stored templates + private static final Pattern STORED_TEMPLATE_ID = Pattern.compile( + "\\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\\b"); + // the original template we are supposed to render private final Template renderTemplate; private final MobileDeviceRepository.DeviceType deviceType; @@ -79,6 +90,8 @@ public VelocityRenderer(Template template, // in the case of a velocity error we want to render an // error page instead so the user knows what was wrong velocityException = ex; + log.warn("Error loading [" + template.getId() + "]: " + + ex.getMessage()); // need to lookup error page template velocityTemplate = RollerVelocity.getTemplate("error-page.vm", deviceType); @@ -102,16 +115,19 @@ public VelocityRenderer(Template template, public void render(Map model, Writer out) throws RenderingException { - try { + if (velocityException != null) { - if (velocityException != null) { + // Render exception + renderException(model, out, null); - // Render exception - renderException(model, out, null); + // and we're done + return; + } - // and we're done - return; - } + // the session bounds output and time, and scopes stored templates + // loaded by #parse and #include to the weblog being rendered + RenderSession session = RenderSession.begin(weblogIdFor(model)); + try { long startTime = System.currentTimeMillis(); @@ -127,7 +143,7 @@ public void render(Map model, Writer out) // render base template to a temporary StringWriter StringWriter sw = new StringWriter(); - velocityTemplate.merge(ctx, sw); + velocityTemplate.merge(ctx, new RenderLimitWriter(sw, session)); // put rendered template into context ctx.put("decorator_body", sw.toString()); @@ -135,12 +151,12 @@ public void render(Map model, Writer out) log.debug("Applying decorator " + velocityDecorator.getName()); // now render decorator to our output writer - velocityDecorator.merge(ctx, out); + velocityDecorator.merge(ctx, new RenderLimitWriter(out, session)); } else { // no decorator, so just merge template to our output writer - velocityTemplate.merge(ctx, out); + velocityTemplate.merge(ctx, new RenderLimitWriter(out, session)); } long endTime = System.currentTimeMillis(); @@ -148,20 +164,81 @@ public void render(Map model, Writer out) log.debug("Rendered [" + renderTemplate.getId() + "] in " + renderTime + " secs"); + return; - } catch (VelocityException ex) { + } catch (Exception ex) { + RenderLimitException limit = findLimit(ex); + if (limit != null) { + // the partial output is discarded by the caller, which + // fails the request as for any other rendering error + log.error("Stopped rendering [" + renderTemplate.getId() + + "]: " + limit.getMessage()); + throw new RenderingException("Error during rendering", limit); + } + if (!(ex instanceof VelocityException)) { + // wrap and rethrow so caller can deal with it + throw new RenderingException("Error during rendering", ex); + } // in the case of a velocity error including a page we want to // render an error page instead so the user knows what was wrong velocityException = ex; + log.warn("Error rendering [" + renderTemplate.getId() + "]: " + + ex.getMessage()); - // need to lookup parse error template - renderException(model, out, "error-parse.vm"); + } finally { + session.end(); + } - } catch (Exception ex) { - // wrap and rethrow so caller can deal with it - throw new RenderingException("Error during rendering", ex); + // need to lookup parse error template + renderException(model, out, "error-parse.vm"); + } + + /** + * @return the id of the weblog being rendered, from the template when it + * is one of the weblog's own, otherwise from the page model; null + * when the render is not for a weblog + */ + private String weblogIdFor(Map model) { + if (renderTemplate instanceof WeblogTemplate) { + Weblog weblog = ((WeblogTemplate) renderTemplate).getWeblog(); + return weblog == null ? null : weblog.getId(); + } + Object pageModel = model == null ? null : model.get("model"); + WeblogWrapper weblog = null; + if (pageModel instanceof PageModel) { + weblog = ((PageModel) pageModel).getWeblog(); + } else if (pageModel instanceof FeedModel) { + weblog = ((FeedModel) pageModel).getWeblog(); + } else if (pageModel instanceof SearchResultsFeedModel) { + weblog = ((SearchResultsFeedModel) pageModel).getWeblog(); + } + return weblog == null ? null : weblog.getId(); + } + + /** + * @return the exception's message as the public error page shows it, with + * template ids replaced by the template's name, or by "template" + * for other stored templates; the ids stay in the log + */ + private String publicMessage(Exception ex) { + String message = 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"); + } + + 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 +267,7 @@ private void renderException(Map model, Writer out, Context ctx = new VelocityContext(model); ctx.put("exception", velocityException); - ctx.put("exceptionSource", renderTemplate.getId()); + ctx.put("exceptionMessage", publicMessage(velocityException)); ctx.put("exceptionDevice", deviceType); ctx.put("utils", new UtilitiesModel()); diff --git a/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties b/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties index e4e92d10cb..568c61ffab 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 @@ -489,6 +489,12 @@ org.apache.roller.weblogger.ui.rendering.model.PlanetModel # Velocity settings velocity.properties=/WEB-INF/velocity.properties +# Limits on rendering one weblog page or feed. A template that writes more +# characters (or builds a longer string) than maxOutputChars, or takes longer +# than maxRenderSeconds, fails with an error in the log. Zero means no limit. +rendering.maxOutputChars=10485760 +rendering.maxRenderSeconds=30 + #----------------------------------------------------------------------------- # Weblog ping system #----------------------------------------------------------------------------- diff --git a/app/src/main/webapp/WEB-INF/velocity.properties b/app/src/main/webapp/WEB-INF/velocity.properties index 190a7bbbca..0ac1331022 100644 --- a/app/src/main/webapp/WEB-INF/velocity.properties +++ b/app/src/main/webapp/WEB-INF/velocity.properties @@ -62,14 +62,30 @@ velocimacro.library.autoreload=false # Allow Velocimacros to be defined in regular templates velocimacro.inline.allow=true -# Allow template authors to define macros in any template -velocimacro.inline.local_scope=false +# Macros a template defines belong to that template, and to the render it +# starts, so one weblog's macro never replaces another's of the same name and +# an edited macro takes effect on the next render. With replace_global, the +# page's macros are also seen by the templates it #parses, and a macro +# defined in a #parse'd template is seen by the rest of the page, as before. +# Library macros (velocimacro.library.path) stay global. +velocimacro.inline.local_scope=true +velocimacro.inline.replace_global=true # set encoding/charset to UTF-8 resource.default_encoding=UTF-8 default.contentType=text/html; charset=utf-8 -introspector.uberspect.class=org.apache.velocity.util.introspection.SecureUberspector +# Weblog templates are written by weblog authors, so a render is bounded. +# RenderLimitUberspector, chained after SecureUberspector, checks the render +# deadline on method calls and refuses String.repeat; RollerForeach checks it +# on every #foreach pass, which also stops after max_loops passes; and every +# inserted value is checked against the output limit. The limits themselves +# are rendering.maxOutputChars and rendering.maxRenderSeconds in +# roller.properties. +introspector.uberspect.class=org.apache.velocity.util.introspection.SecureUberspector,org.apache.roller.weblogger.ui.rendering.velocity.RenderLimitUberspector +runtime.custom_directives=org.apache.roller.weblogger.ui.rendering.velocity.RollerForeach +directive.foreach.max_loops=100000 +event_handler.reference_insertion.class=org.apache.roller.weblogger.ui.rendering.velocity.RenderLimitInsertionHandler # SecureUberspector governs method access, not resource resolution, so the # include directives are confined separately. diff --git a/app/src/main/webapp/WEB-INF/velocity/templates/error-page.vm b/app/src/main/webapp/WEB-INF/velocity/templates/error-page.vm index 94b84fee99..194bddbadc 100644 --- a/app/src/main/webapp/WEB-INF/velocity/templates/error-page.vm +++ b/app/src/main/webapp/WEB-INF/velocity/templates/error-page.vm @@ -69,11 +69,7 @@ Message - $utils.autoformat($utils.escapeHTML($exception.getMessage())) - - - Type - $exceptionSource + $utils.autoformat($utils.escapeHTML($exceptionMessage)) Exception diff --git a/app/src/main/webapp/WEB-INF/velocity/templates/error-parse.vm b/app/src/main/webapp/WEB-INF/velocity/templates/error-parse.vm index bdb378e8a9..fa466cc5a4 100644 --- a/app/src/main/webapp/WEB-INF/velocity/templates/error-parse.vm +++ b/app/src/main/webapp/WEB-INF/velocity/templates/error-parse.vm @@ -34,11 +34,7 @@ Message - $utils.autoformat($utils.escapeHTML($exception.getMessage())) - - - Type - $exceptionSource + $utils.autoformat($utils.escapeHTML($exceptionMessage)) Exception diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitsTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitsTest.java new file mode 100644 index 0000000000..d645f88983 --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitsTest.java @@ -0,0 +1,165 @@ +/* + * 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 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 { + RollerVelocityTestSupport.addTemplate(name, source); + Outcome outcome = new Outcome(); + VelocityRenderer renderer = new VelocityRenderer( + RollerVelocityTestSupport.page(name), DeviceType.standard); + try { + renderer.render(new HashMap<>(), outcome.out); + } catch (RenderingException ex) { + outcome.failure = ex; + } + return outcome; + } + + private static boolean reachedTestCeiling(Throwable t) { + for (; t != null; t = t.getCause()) { + if (t instanceof IllegalStateException + && "test ceiling reached".equals(t.getMessage())) { + return true; + } + } + return false; + } + + 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"); + } + + @Test + public void aHugeForeachRangeStopsAtTheLoopLimit() { + assertTimeoutPreemptively(WITHIN, () -> { + Outcome outcome = render("limits-foreach.vm", + "#foreach($i in [1..2000000000])0123456789#end"); + assertFalse(reachedTestCeiling(outcome.failure), + "only the test's own ceiling stopped rendering"); + assertTrue(outcome.out.getCount() <= 100000 * 10, + "#foreach ran past 100000 passes: wrote " + outcome.out.getCount()); + }); + } + + @Test + public void nestedLoopsStopAtTheOutputLimit() { + assertTimeoutPreemptively(WITHIN, () -> assertStoppedByRoller(render( + "limits-nested.vm", + "#foreach($i in [1..100000])#foreach($j in [1..100000])" + + "0123456789#end#end"))); + } + + @Test + public void limitsApplyInsideMacrosAndParsedTemplates() { + RollerVelocityTestSupport.addTemplate("limits-parsed.vm", "#spin()"); + assertTimeoutPreemptively(WITHIN, () -> assertStoppedByRoller(render( + "limits-macro.vm", + "#macro(spin)#foreach($i in [1..100000])#foreach($j in [1..100000])" + + "0123456789#end#end#end#parse('limits-parsed.vm')"))); + } + + @Test + public void aLoopThatWritesNothingStopsAtTheDeadline() { + assertTimeoutPreemptively(WITHIN, () -> { + Outcome outcome = render("limits-deadline.vm", + "#foreach($i in [1..100000])#foreach($j in [1..100000])" + + "#set($k = $j)#end#end"); + assertNotNull(outcome.failure, "rendering should have failed"); + }); + } + + @Test + public void aStringDoubledInPlaceStopsAtTheSizeLimit() { + assertTimeoutPreemptively(WITHIN, () -> { + Outcome outcome = render("limits-doubling.vm", + "#set($s = '0123456789')" + + "#foreach($i in [1..22])#set($s = \"$s$s\")#end$s.length()"); + assertNotNull(outcome.failure, + "rendering should have failed, but wrote " + outcome.out.getHead()); + }); + } + + @Test + public void stringRepeatIsNotAvailableToTemplates() { + assertTimeoutPreemptively(WITHIN, () -> { + Outcome outcome = render("limits-repeat.vm", + "#set($s = '0123456789')" + + "$s.repeat(3000000)$s.repeat(3000000)$s.repeat(3000000)"); + assertFalse(reachedTestCeiling(outcome.failure), + "String.repeat filled the output"); + assertTrue(outcome.out.getCount() < 1024 * 1024, + "String.repeat wrote " + outcome.out.getCount() + " chars"); + assertFalse(outcome.out.getHead().contains("01234567890123456789"), + "String.repeat ran: " + outcome.out.getHead()); + }); + } + + /** The limits are chained after SecureUberspector, which still applies. */ + @Test + public void theIntrospectionSandboxStillApplies() throws Exception { + Outcome outcome = render("limits-sandbox.vm", + "#set($s = 'x')[$s.class.classLoader]" + + "[$s.getClass().forName('java.lang.Runtime')]"); + assertEquals("[$s.class.classLoader][$s.getClass().forName('java.lang.Runtime')]", + outcome.out.getHead()); + } +} diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerVelocityTestSupport.java b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerVelocityTestSupport.java new file mode 100644 index 0000000000..9fa5e2dff9 --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerVelocityTestSupport.java @@ -0,0 +1,173 @@ +/* + * 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.concurrent.ConcurrentHashMap; + +import javax.servlet.ServletContext; + +import org.apache.roller.weblogger.pojos.Template; +import org.apache.roller.weblogger.pojos.TemplateRendition; +import org.apache.roller.weblogger.pojos.TemplateRendition.RenditionType; +import org.apache.roller.weblogger.ui.core.RollerContext; + +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Lets tests drive the real {@link RollerVelocity} engine, configured from the + * shipped WEB-INF/velocity.properties, without a servlet container. Files under + * src/main/webapp are served as they are; a test can add its own templates, + * which are served from /WEB-INF/velocity/ by name. + */ +final class RollerVelocityTestSupport { + + private static final Path WEBAPP = Paths.get( + System.getProperty("project.basedir", System.getProperty("user.dir")), + "src", "main", "webapp"); + + private static final String TEMPLATE_DIR = "/WEB-INF/velocity/"; + + private static final Map TEMPLATES = new ConcurrentHashMap<>(); + + private static boolean installed = false; + + private RollerVelocityTestSupport() { + } + + /** Points RollerContext at a servlet context that serves the webapp. */ + static synchronized void install() throws Exception { + if (installed) { + return; + } + ServletContext context = mock(ServletContext.class); + when(context.getResourceAsStream(anyString())) + .thenAnswer(inv -> open(inv.getArgument(0))); + Field field = RollerContext.class.getDeclaredField("servletContext"); + field.setAccessible(true); + field.set(null, context); + installed = true; + } + + /** 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 0000000000..d595e6e361 --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/WeblogTemplateScopeTest.java @@ -0,0 +1,268 @@ +/* + * 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.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.assertTrue; + +/** + * Renders weblogs' own stored templates through the shipped engine and + * VelocityRenderer, as the page servlets do, to check that one weblog's + * templates and macros stay its own: another weblog cannot read them with + * #include or #parse, or replace them by defining a macro of the same name. + */ +public class WeblogTemplateScopeTest { + + private static final Log LOG = LogFactory.getLog(WeblogTemplateScopeTest.class); + + private User userA; + private User userB; + private Weblog weblogA; + private Weblog weblogB; + + /** The page model a weblog template sees, reduced to what these use. */ + public static class StubModel { + private final WeblogWrapper weblog; + + StubModel(Weblog weblog) { + this.weblog = WeblogWrapper.wrap(weblog, + WebloggerFactory.getWeblogger().getUrlStrategy()); + } + + public WeblogWrapper getWeblog() { + return weblog; + } + + public String getDeviceType() { + return DeviceType.standard.toString(); + } + } + + @BeforeEach + public void setUp() throws Exception { + TestUtils.setupWeblogger(); + RollerVelocityTestSupport.install(); + try { + userA = TestUtils.setupUser("scopeRenderUserA"); + userB = TestUtils.setupUser("scopeRenderUserB"); + weblogA = customTheme(TestUtils.setupWeblog("scopeRenderWeblogA", userA)); + weblogB = customTheme(TestUtils.setupWeblog("scopeRenderWeblogB", userB)); + TestUtils.endSession(true); + } catch (Exception ex) { + LOG.error(ex); + throw new Exception("Test setup failed", ex); + } + } + + @AfterEach + public void tearDown() throws Exception { + try { + TestUtils.teardownWeblog(weblogA.getId()); + TestUtils.teardownWeblog(weblogB.getId()); + TestUtils.teardownUser(userA.getUserName()); + TestUtils.teardownUser(userB.getUserName()); + TestUtils.endSession(true); + } catch (Exception ex) { + LOG.error(ex); + throw new Exception("Test teardown failed", ex); + } + } + + private static Weblog customTheme(Weblog weblog) throws Exception { + weblog.setEditorTheme(WeblogTheme.CUSTOM); + WebloggerFactory.getWeblogger().getWeblogManager().saveWeblog(weblog); + return weblog; + } + + private static String createTemplate(Weblog weblog, String name, String source) + throws Exception { + WeblogTemplate template = new WeblogTemplate(); + template.setAction(ComponentType.CUSTOM); + template.setName(name); + template.setDescription(name); + template.setLastModified(new java.util.Date()); + template.setWeblog(TestUtils.getManagedWebsite(weblog)); + CustomTemplateRendition rendition = + new CustomTemplateRendition(template, RenditionType.STANDARD); + rendition.setTemplate(source); + rendition.setTemplateLanguage(TemplateLanguage.VELOCITY); + WebloggerFactory.getWeblogger().getWeblogManager().saveTemplate(template); + TestUtils.endSession(true); + return template.getId(); + } + + private static void editTemplate(String id, String source) throws Exception { + WeblogManager mgr = WebloggerFactory.getWeblogger().getWeblogManager(); + CustomTemplateRendition rendition = mgr.getTemplate(id) + .getTemplateRendition(RenditionType.STANDARD); + rendition.setTemplate(source); + mgr.saveTemplateRendition(rendition); + TestUtils.endSession(true); + } + + private static String render(Weblog weblog, String templateId) throws Exception { + WeblogTemplate template = WebloggerFactory.getWeblogger().getWeblogManager() + .getTemplate(templateId); + Map model = new HashMap<>(); + model.put("model", new StubModel(TestUtils.getManagedWebsite(weblog))); + StringWriter out = new StringWriter(); + new VelocityRenderer(template, DeviceType.standard).render(model, out); + return out.toString(); + } + + @Test + public void includeCannotReadAnotherWeblogsTemplate() throws Exception { + String secret = createTemplate(weblogB, "secret", "B-PRIVATE-SOURCE #set($x = 1)"); + String page = createTemplate(weblogA, "page", "[#include(\"" + secret + "|standard\")]"); + + String output = render(weblogA, page); + assertFalse(output.contains("B-PRIVATE-SOURCE"), + "#include returned another weblog's template:\n" + output); + } + + @Test + public void parseCannotRenderAnotherWeblogsTemplate() throws Exception { + String secret = createTemplate(weblogB, "secret", "B-PRIVATE-SOURCE"); + String page = createTemplate(weblogA, "page", "[#parse(\"" + secret + "|standard\")]"); + + String output = render(weblogA, page); + assertFalse(output.contains("B-PRIVATE-SOURCE"), + "#parse rendered another weblog's template:\n" + output); + } + + @Test + public void aWeblogCanStillIncludeItsOwnTemplates() throws Exception { + String part = createTemplate(weblogA, "part", "A-PART"); + String page = createTemplate(weblogA, "page", + "[#include(\"" + part + "|standard\")]" + + "[#parse(\"" + part + "|standard\")]" + + "[#includeTemplate($model.weblog \"part\")]"); + + assertEquals("[A-PART][A-PART][A-PART]", render(weblogA, page).trim()); + } + + @Test + public void errorPageDoesNotShowTemplateIds() throws Exception { + String page = createTemplate(weblogA, "broken-page", "#foreach("); + String part = createTemplate(weblogA, "broken-part", "#foreach("); + String includer = createTemplate(weblogA, "includer", + "#includeTemplate($model.weblog \"broken-part\")"); + + String output = render(weblogA, page); + assertTrue(output.contains("Velocity template error"), + "expected the error page:\n" + output); + assertFalse(output.contains(page), "the error page showed the template id:\n" + output); + assertTrue(output.contains("line 1, column"), + "the error page should still say where the error is:\n" + output); + + output = render(weblogA, includer); + assertTrue(output.contains("Velocity template error"), + "expected the error page:\n" + output); + assertFalse(output.contains(includer) || output.contains(part), + "the error page showed a template id:\n" + output); + } + + @Test + public void inlineMacrosBelongToTheWeblogThatDefinesThem() throws Exception { + String pageA = createTemplate(weblogA, "page", "#macro(scopeProbe)A-MACRO#end[#scopeProbe()]"); + String pageB = createTemplate(weblogB, "page", "#macro(scopeProbe)B-MACRO#end[#scopeProbe()]"); + + assertEquals("[A-MACRO]", render(weblogA, pageA).trim()); + assertEquals("[B-MACRO]", render(weblogB, pageB).trim(), + "weblog B rendered weblog A's macro"); + assertEquals("[A-MACRO]", render(weblogA, pageA).trim()); + + editTemplate(pageA, "#macro(scopeProbe)A-EDITED#end[#scopeProbe()]"); + assertEquals("[A-EDITED]", render(weblogA, pageA).trim(), + "an edited macro was not picked up"); + assertEquals("[B-MACRO]", render(weblogB, pageB).trim()); + } + + @Test + public void anInlineMacroDoesNotReplaceALibraryMacroForOtherWeblogs() throws Exception { + String pageA = createTemplate(weblogA, "page", + "#macro(includeTemplate $weblog $name)A-REPLACED#end" + + "[#includeTemplate($model.weblog \"part\")]"); + createTemplate(weblogB, "part", "B-PART"); + String pageB = createTemplate(weblogB, "page", + "[#includeTemplate($model.weblog \"part\")]"); + + assertEquals("[A-REPLACED]", render(weblogA, pageA).trim()); + assertEquals("[B-PART]", render(weblogB, pageB).trim(), + "weblog A's macro replaced the library macro for weblog B"); + } + + @Test + public void macrosStillReachAcrossAWeblogsOwnTemplates() throws Exception { + createTemplate(weblogA, "macros", "#macro(fromLibrary)LIB-OF-A#end"); + createTemplate(weblogA, "child", "[child:#fromParent()]"); + createTemplate(weblogA, "uses-library", "[sibling:#fromLibrary()]"); + String defs = createTemplate(weblogA, "defs", "#macro(fromDefs)DEFS-OF-A#end"); + + // a macro defined in a template the page includes, through the + // library macro themes use and through #parse directly + String viaIncludeTemplate = createTemplate(weblogA, "page1", + "#includeTemplate($model.weblog \"macros\")[#fromLibrary()]"); + assertEquals("[LIB-OF-A]", render(weblogA, viaIncludeTemplate).trim()); + + String viaParse = createTemplate(weblogA, "page2", + "#parse(\"" + defs + "|standard\")[#fromDefs()]"); + assertEquals("[DEFS-OF-A]", render(weblogA, viaParse).trim()); + + // a macro the page defines, called from a template it includes + String parentToChild = createTemplate(weblogA, "page3", + "#macro(fromParent)PARENT-OF-A#end#includeTemplate($model.weblog \"child\")"); + assertEquals("[child:PARENT-OF-A]", render(weblogA, parentToChild).trim()); + + // a macro one included template defines, called from the next + String siblings = createTemplate(weblogA, "page4", + "#includeTemplate($model.weblog \"macros\")" + + "#includeTemplate($model.weblog \"uses-library\")"); + assertEquals("[sibling:LIB-OF-A]", render(weblogA, siblings).trim()); + + // weblog B does not see any of weblog A's macros + String pageB = createTemplate(weblogB, "page", "[#fromLibrary()]"); + assertEquals("[#fromLibrary()]", render(weblogB, pageB).trim()); + } +} diff --git a/app/src/test/resources/WEB-INF/velocity.properties b/app/src/test/resources/WEB-INF/velocity.properties index 4c218366fe..6a0a7d96b0 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 @@ -72,5 +78,15 @@ default.contentType=text/html; charset=utf-8 # Weblog templates render under SecureUberspector, which governs method access # rather than resource resolution, so the include directives are confined # separately. Keep this aligned with /WEB-INF/velocity.properties. -introspector.uberspect.class=org.apache.velocity.util.introspection.SecureUberspector +# Weblog templates are written by weblog authors, so a render is bounded. +# RenderLimitUberspector, chained after SecureUberspector, checks the render +# deadline on method calls and refuses String.repeat; RollerForeach checks it +# on every #foreach pass, which also stops after max_loops passes; and every +# inserted value is checked against the output limit. The limits themselves +# are rendering.maxOutputChars and rendering.maxRenderSeconds in +# roller.properties. +introspector.uberspect.class=org.apache.velocity.util.introspection.SecureUberspector,org.apache.roller.weblogger.ui.rendering.velocity.RenderLimitUberspector +runtime.custom_directives=org.apache.roller.weblogger.ui.rendering.velocity.RollerForeach +directive.foreach.max_loops=100000 +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 23a2c28db2..659040ec33 100644 --- a/app/src/test/resources/roller-custom.properties +++ b/app/src/test/resources/roller-custom.properties @@ -42,3 +42,6 @@ tasks.TestTask.class=org.apache.roller.weblogger.business.TestTask tasks.TestTask.startTime=immediate tasks.TestTask.interval=1800 tasks.TestTask.leaseTime=300 + +# Keep render-deadline tests short. +rendering.maxRenderSeconds=5 From 1347a7fc561e8ec073205f04357634c3e954176f Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Tue, 17 Nov 2026 19:53:33 -0700 Subject: [PATCH 02/18] Stop string calls from templates that would build a string past the output limit before they run String.replace, replaceAll, replaceFirst, concat, toUpperCase and toLowerCase, $utils.replace, and StringBuilder and StringBuffer growth methods now work out the longest string they can build before running, and the render stops with the output limit error when that is over the limit. String.format, formatted, join and indent are not offered to templates, like String.repeat, along with any other String method returning a string whose length can't be worked out from the call. Ordinary replaces and other string calls work as before. --- .../velocity/RenderLimitUberspector.java | 22 +- .../ui/rendering/velocity/StringGrowth.java | 228 ++++++++++++++++++ .../rendering/velocity/RenderLimitsTest.java | 87 ++++++- .../rendering/velocity/StringGrowthTest.java | 132 ++++++++++ 4 files changed, 462 insertions(+), 7 deletions(-) create mode 100644 app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java create mode 100644 app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitUberspector.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitUberspector.java index 5925f4c75f..33402a1cdc 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitUberspector.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitUberspector.java @@ -33,8 +33,10 @@ /** * Chained after SecureUberspector, this keeps method calls from templates * inside the render limits: each call and property read checks the deadline, - * a string a call returns may be no longer than the output limit, and - * String.repeat, which can build a huge string in one call, is not offered. + * a string a call returns may be no longer than the output limit, a call that + * could build a longer string is stopped before it runs, and string methods + * whose result can't be bounded from the call (String.repeat, String.format + * and others; see StringGrowth) are not offered. */ public class RenderLimitUberspector extends AbstractChainableUberspector { @@ -48,12 +50,16 @@ public Iterator getIterator(Object obj, Info i) { @Override public VelMethod getMethod(Object obj, String methodName, Object[] args, Info i) { - if (obj instanceof String && "repeat".equals(methodName)) { - LOG.debug("Refusing String.repeat at " + i); + VelMethod method = super.getMethod(obj, methodName, args, i); + if (method == null) { return null; } - VelMethod method = super.getMethod(obj, methodName, args, i); - return method == null ? null : new LimitedMethod(method); + if (StringGrowth.isRefused(obj, methodName, method.getReturnType())) { + LOG.debug("Refusing " + obj.getClass().getSimpleName() + "." + methodName + + " at " + i); + return null; + } + return new LimitedMethod(method); } @Override @@ -81,6 +87,10 @@ private static final class LimitedMethod implements VelMethod { public Object invoke(Object o, Object[] params) throws IllegalAccessException, InvocationTargetException { RenderSession.checkDeadline(); + if (RenderSession.current() != null) { + RenderSession.checkLength(StringGrowth.maxResultLength( + o, method.getMethodName(), params)); + } return checked(method.invoke(o, params)); } diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java new file mode 100644 index 0000000000..d0db017016 --- /dev/null +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java @@ -0,0 +1,228 @@ +/* + * 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.Set; + +import org.apache.roller.weblogger.ui.rendering.model.UtilitiesModel; + +/** + * Some string methods build a result much longer than their receiver and + * arguments, so checking the result's length after the call is too late. This + * works out, before a call from a template runs, the longest string it can + * build, and names the methods whose result can't be bounded that way. + * + *

Methods are matched by name so that methods added in later Java versions + * (String.indent, String.formatted, StringBuilder.repeat) are covered when + * Roller runs on them. + */ +final class StringGrowth { + + /** String methods that are not offered to templates. */ + private static final Set REFUSED_STRING_METHODS = Set.of( + "repeat", "format", "formatted", "join", "indent"); + + /** String methods whose result is never longer than the receiver or an argument. */ + private static final Set NON_GROWING_STRING_METHODS = Set.of( + "substring", "subSequence", "trim", "strip", "stripLeading", + "stripTrailing", "stripIndent", "translateEscapes", "intern", + "toString", "valueOf", "copyValueOf"); + + /** StringBuilder and StringBuffer methods that are not offered to templates. */ + private static final Set REFUSED_BUILDER_METHODS = Set.of("repeat"); + + /** Characters a number, boolean or other value appended to a builder may take. */ + private static final long SCALAR_LENGTH = 32; + + /** Most characters toUpperCase or toLowerCase makes of one character. */ + private static final long CASE_GROWTH = 3; + + private StringGrowth() { + } + + /** + * @return true if the method must not be offered on this receiver: it can + * build a string whose length can't be worked out from the call + */ + static boolean isRefused(Object receiver, String methodName, Class returnType) { + if (receiver instanceof String) { + if (REFUSED_STRING_METHODS.contains(methodName)) { + return true; + } + // a method this class doesn't know about that returns a string + return returnType != null && CharSequence.class.isAssignableFrom(returnType) + && !NON_GROWING_STRING_METHODS.contains(methodName) + && !isBoundedStringMethod(methodName); + } + if (receiver instanceof StringBuilder || receiver instanceof StringBuffer) { + return REFUSED_BUILDER_METHODS.contains(methodName); + } + return false; + } + + private static boolean isBoundedStringMethod(String methodName) { + switch (methodName) { + case "replace": + case "replaceAll": + case "replaceFirst": + case "concat": + case "toUpperCase": + case "toLowerCase": + return true; + default: + return false; + } + } + + /** + * @return the most characters the call can put in one string, or 0 when + * it doesn't build a string longer than its receiver or arguments + */ + static long maxResultLength(Object receiver, String methodName, Object[] args) { + Object[] a = args == null ? new Object[0] : args; + if (receiver instanceof String) { + return forString((String) receiver, methodName, a); + } + if (receiver instanceof StringBuilder || receiver instanceof StringBuffer) { + return forBuilder((CharSequence) receiver, methodName, a); + } + if (receiver instanceof UtilitiesModel && "replace".equals(methodName) + && a.length >= 3 && a[0] instanceof String) { + long maxCount = a.length > 3 && a[3] instanceof Number + ? ((Number) a[3]).longValue() : -1; + if (!(a[1] instanceof String) || ((String) a[1]).isEmpty()) { + // StringUtils.replace leaves the text alone for an empty target + return 0; + } + return literalReplace((String) a[0], (String) a[1], length(a[2]), maxCount); + } + return 0; + } + + private static long forString(String s, String methodName, Object[] a) { + long len = s.length(); + switch (methodName) { + case "replace": + if (a.length == 2 && a[0] instanceof CharSequence) { + return literalReplace(s, a[0].toString(), length(a[1]), -1); + } + return len; + case "replaceAll": + case "replaceFirst": { + // each match adds the replacement, and each group reference + // in it ($1, ${name}) can add up to the whole receiver; an + // empty pattern matches len + 1 times + long repl = length(a.length > 1 ? a[1] : null); + long refs = count(a.length > 1 ? a[1] : null, '$'); + long perMatch = add(repl, multiply(refs, len)); + long matches = "replaceAll".equals(methodName) ? len + 1 : 1; + return add(len, multiply(matches, perMatch)); + } + case "concat": + return add(len, length(a.length > 0 ? a[0] : null)); + case "toUpperCase": + case "toLowerCase": + return multiply(CASE_GROWTH, len); + default: + return 0; + } + } + + private static long forBuilder(CharSequence b, String methodName, Object[] a) { + long len = b.length(); + switch (methodName) { + case "setLength": + case "ensureCapacity": + return a.length == 1 && a[0] instanceof Number + ? ((Number) a[0]).longValue() : 0; + case "append": + case "appendCodePoint": + case "insert": + case "replace": { + long total = len; + for (Object arg : a) { + total = add(total, arg instanceof CharSequence || arg instanceof char[] + ? length(arg) : SCALAR_LENGTH); + } + return total; + } + default: + return 0; + } + } + + /** Length of s with up to maxCount (or all, when negative) target occurrences replaced. */ + private static long literalReplace(String s, String target, long replacementLength, + long maxCount) { + long occurrences; + if (target.isEmpty()) { + occurrences = s.length() + 1L; + } else { + occurrences = 0; + for (int i = s.indexOf(target); i >= 0; i = s.indexOf(target, i + target.length())) { + occurrences++; + if (occurrences == maxCount) { + break; + } + } + } + if (maxCount >= 0) { + occurrences = Math.min(occurrences, maxCount); + } + long growth = Math.max(0, replacementLength - target.length()); + return add(s.length(), multiply(occurrences, growth)); + } + + private static long length(Object value) { + if (value instanceof CharSequence) { + return ((CharSequence) value).length(); + } + if (value instanceof char[]) { + return ((char[]) value).length; + } + return value == null ? 0 : SCALAR_LENGTH; + } + + private static long count(Object value, char c) { + if (!(value instanceof CharSequence)) { + return 0; + } + CharSequence cs = (CharSequence) value; + long n = 0; + for (int i = 0; i < cs.length(); i++) { + if (cs.charAt(i) == c) { + n++; + } + } + return n; + } + + private static long add(long a, long b) { + long sum = a + b; + return sum < 0 ? Long.MAX_VALUE : sum; + } + + private static long multiply(long a, long b) { + if (a == 0 || b == 0) { + return 0; + } + return a > Long.MAX_VALUE / b ? Long.MAX_VALUE : a * b; + } +} diff --git a/app/src/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 index d645f88983..244ab93e46 100644 --- 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 @@ -19,10 +19,13 @@ package org.apache.roller.weblogger.ui.rendering.velocity; +import java.lang.management.ManagementFactory; import java.time.Duration; import java.util.HashMap; +import java.util.Map; import org.apache.roller.weblogger.ui.rendering.RenderingException; +import org.apache.roller.weblogger.ui.rendering.model.UtilitiesModel; import org.apache.roller.weblogger.ui.rendering.mobile.MobileDeviceRepository.DeviceType; import org.apache.roller.weblogger.ui.rendering.velocity.RollerVelocityTestSupport.CeilingWriter; import org.junit.jupiter.api.BeforeAll; @@ -58,12 +61,17 @@ private static final class Outcome { } private static Outcome render(String name, String source) throws Exception { + return render(name, source, new HashMap<>()); + } + + private static Outcome render(String name, String source, Map context) + throws Exception { RollerVelocityTestSupport.addTemplate(name, source); Outcome outcome = new Outcome(); VelocityRenderer renderer = new VelocityRenderer( RollerVelocityTestSupport.page(name), DeviceType.standard); try { - renderer.render(new HashMap<>(), outcome.out); + renderer.render(context, outcome.out); } catch (RenderingException ex) { outcome.failure = ex; } @@ -162,4 +170,81 @@ public void theIntrospectionSandboxStillApplies() throws Exception { assertEquals("[$s.class.classLoader][$s.getClass().forName('java.lang.Runtime')]", outcome.out.getHead()); } + + /** A 10,240-character string of digits, 1,024 of them zeros. */ + private static final String TEN_THOUSAND_DIGITS = "#set($s = '0123456789')" + + "#foreach($i in [1..10])#set($s = \"$s$s\")#end"; + + private static long allocatedBytes() { + return ((com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean()) + .getThreadAllocatedBytes(Thread.currentThread().getId()); + } + + /** + * Renders on this thread and returns how many bytes the render allocated, + * after a first render that loads the engine and compiles the template. + */ + private static long allocatedByRender(String name, String source, + Map context) throws Exception { + Outcome warmUp = render(name, source, context); + assertNotNull(warmUp.failure, "rendering should have failed"); + long before = allocatedBytes(); + Outcome outcome = render(name, source, context); + long allocated = allocatedBytes() - before; + assertNotNull(outcome.failure, "rendering should have failed"); + assertFalse(reachedTestCeiling(outcome.failure), + "only the test's own ceiling stopped rendering"); + return allocated; + } + + /** + * Each of these would build a string of about 42 million characters, four + * times the output limit. The call has to be refused before it runs, not + * after the result is built. + */ + @Test + public void growingStringCallsAreRefusedBeforeTheyRun() throws Exception { + String[] calls = { + "$s.replace('0', \"$s$s$s$s\")", + "$s.replaceAll('0', \"$s$s$s$s\")", + "$utils.replace($s, '0', \"$s$s$s$s\")", + }; + Map context = new HashMap<>(); + context.put("utils", new UtilitiesModel()); + for (int i = 0; i < calls.length; i++) { + long allocated = allocatedByRender("limits-growing-" + i + ".vm", + TEN_THOUSAND_DIGITS + calls[i], context); + assertTrue(allocated < 16L * 1024 * 1024, + calls[i] + " allocated " + allocated + " bytes before it was stopped"); + } + } + + /** String.format can pad to any width, so it is not offered. */ + @Test + public void stringFormatIsNotAvailableToTemplates() throws Exception { + Outcome outcome = render("limits-format.vm", + "#set($s = 'x')$s.format('%05000000d', 1)"); + assertFalse(outcome.out.getHead().contains("00000000"), + "String.format ran"); + assertTrue(outcome.out.getCount() < 1024, "String.format wrote " + + outcome.out.getCount() + " chars"); + } + + @Test + public void ordinaryStringCallsStillWork() throws Exception { + Map context = new HashMap<>(); + context.put("utils", new UtilitiesModel()); + Outcome outcome = render("limits-ordinary.vm", + "#set($s = 'Hello, World')" + + "[$s.replace('o', '0')][$s.replace('', '-')][$s.replaceAll('[A-Z]', '_')]" + + "[$s.replaceFirst('l+', 'L')][$s.concat('!')][$s.toUpperCase()]" + + "[$s.toLowerCase()][$s.substring(7)][$s.trim()]" + + "[$utils.replace($s, ' ', '_')]", + context); + assertEquals(null, outcome.failure); + assertEquals("[Hell0, W0rld][-H-e-l-l-o-,- -W-o-r-l-d-][_ello, _orld]" + + "[HeLo, World][Hello, World!][HELLO, WORLD]" + + "[hello, world][World][Hello, World]" + + "[Hello,_World]", outcome.out.getHead()); + } } diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java new file mode 100644 index 0000000000..691484feed --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java @@ -0,0 +1,132 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.roller.weblogger.ui.rendering.velocity; + +import java.util.Locale; + +import org.apache.roller.weblogger.ui.rendering.model.UtilitiesModel; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The bound worked out before a string call has to be at least the length the + * call really produces. These run each call on small strings and compare. + */ +class StringGrowthTest { + + private static final String[] TEXTS = {"", "a", "ab", "aaaa", "Hello, World", "ßßß ff İ"}; + private static final String[] PATTERNS = {"", "a", "l+", "(?=(.*))", "(.)", "\\b", "$"}; + private static final String[] REPLACEMENTS = {"", "x", "xyz", "$0", "$1$1", "${g}", "\\$"}; + + private static void assertBounds(String what, String actual, long bound) { + assertTrue(bound >= actual.length(), + what + " produced " + actual.length() + " chars, bound was " + bound); + } + + @Test + void literalReplaceIsExact() { + for (String s : TEXTS) { + for (String target : REPLACEMENTS) { + for (String r : REPLACEMENTS) { + String actual = s.replace(target, r); + long bound = StringGrowth.maxResultLength(s, "replace", new Object[] {target, r}); + assertEquals(Math.max(s.length(), actual.length()), bound, + "'" + s + "'.replace('" + target + "', '" + r + "')"); + } + } + } + } + + @Test + void regexReplaceIsBounded() { + for (String s : TEXTS) { + for (String p : PATTERNS) { + for (String r : REPLACEMENTS) { + if (r.contains("${g}") || (r.contains("$1") && !p.contains("("))) { + continue; // no such group: the call throws + } + Object[] args = {p, r}; + assertBounds("replaceAll", s.replaceAll(p, r), + StringGrowth.maxResultLength(s, "replaceAll", args)); + assertBounds("replaceFirst", s.replaceFirst(p, r), + StringGrowth.maxResultLength(s, "replaceFirst", args)); + } + } + } + } + + @Test + void caseChangesAndConcatAreBounded() { + for (String s : TEXTS) { + for (Locale l : new Locale[] {Locale.ROOT, new Locale("tr"), Locale.GERMAN}) { + assertBounds("toUpperCase", s.toUpperCase(l), + StringGrowth.maxResultLength(s, "toUpperCase", new Object[] {l})); + assertBounds("toLowerCase", s.toLowerCase(l), + StringGrowth.maxResultLength(s, "toLowerCase", new Object[] {l})); + } + assertBounds("concat", s.concat(s), + StringGrowth.maxResultLength(s, "concat", new Object[] {s})); + } + } + + @Test + void utilitiesReplaceIsExact() { + UtilitiesModel utils = new UtilitiesModel(); + assertEquals(3 + 2 * 3, StringGrowth.maxResultLength(utils, "replace", + new Object[] {"a.a", "a", "xyzw"})); + assertEquals(3 + 3, StringGrowth.maxResultLength(utils, "replace", + new Object[] {"a.a", "a", "xyzw", 1})); + assertEquals(0, StringGrowth.maxResultLength(utils, "replace", + new Object[] {"a.a", "", "xyzw"})); + } + + @Test + void builderGrowthIsBounded() { + StringBuilder b = new StringBuilder("abc"); + assertEquals(3 + 5, StringGrowth.maxResultLength(b, "append", new Object[] {"hello"})); + assertEquals(1_000_000_000L, StringGrowth.maxResultLength(b, "setLength", + new Object[] {1_000_000_000})); + assertTrue(StringGrowth.isRefused(b, "repeat", StringBuilder.class)); + } + + @Test + void hugeBoundsDoNotOverflow() { + String s = "0".repeat(100_000); + String r = "$0".repeat(50_000); + long bound = StringGrowth.maxResultLength(s, "replaceAll", new Object[] {"", r}); + assertTrue(bound > Integer.MAX_VALUE, "bound was " + bound); + } + + @Test + void unboundableStringMethodsAreRefused() { + for (String name : new String[] {"repeat", "format", "formatted", "join", "indent"}) { + assertTrue(StringGrowth.isRefused("x", name, String.class), name); + } + assertTrue(StringGrowth.isRefused("x", "someNewMethod", String.class)); + for (String name : new String[] {"replace", "substring", "trim", "toUpperCase", "valueOf"}) { + assertFalse(StringGrowth.isRefused("x", name, String.class), name); + } + assertFalse(StringGrowth.isRefused("x", "length", int.class)); + assertFalse(StringGrowth.isRefused("x", "split", String[].class)); + } +} From 4ff363c3af2177d7b182227f4f5e134a5e06aadd Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Tue, 17 Nov 2026 20:06:01 -0700 Subject: [PATCH 03/18] Keep strings built in memory, macro calls and regular expressions inside the render limits String literals such as "$a$b", the + operator, and #define blocks or macro bodies used as strings now stop at the output limit while the string is built, through a parser (RenderLimitParser, set as parser.class) that swaps in nodes which count what they write into a buffer and check the length of two strings before + joins them. Variables set from a template may hold no string longer than the limit. Every variable read and write and every macro call now checks the render deadline, so a recursive macro that writes nothing and calls no methods stops in time, and regular expressions given to String.matches, replaceAll, replaceFirst and split check the deadline as they run, so a slow expression stops with the render. RollerResourceLoader now refuses to start with resource.loader.roller.cache=true, which each weblog rendering only its own templates relies on. --- .../ui/rendering/velocity/DeadlineRegex.java | 103 ++++++++ .../velocity/RenderLimitContext.java | 59 +++++ .../rendering/velocity/RenderLimitParser.java | 233 ++++++++++++++++++ .../velocity/RenderLimitUberspector.java | 9 +- .../velocity/RollerResourceLoader.java | 9 +- .../rendering/velocity/VelocityRenderer.java | 4 +- .../main/webapp/WEB-INF/velocity.properties | 3 + .../rendering/velocity/DeadlineRegexTest.java | 64 +++++ .../rendering/velocity/RenderLimitsTest.java | 83 +++++++ .../velocity/WeblogTemplateScopeTest.java | 19 ++ .../resources/WEB-INF/velocity.properties | 3 + 11 files changed, 585 insertions(+), 4 deletions(-) create mode 100644 app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java create mode 100644 app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitContext.java create mode 100644 app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitParser.java create mode 100644 app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegexTest.java diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java new file mode 100644 index 0000000000..a45f0261b2 --- /dev/null +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java @@ -0,0 +1,103 @@ +/* + * 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.regex.Pattern; + +/** + * Runs the String methods that take a regular expression (matches, + * replaceAll, replaceFirst and split) over text that checks the render + * deadline as the expression reads it, so a slow expression stops with the + * render instead of holding the thread. Each gives the same result as the + * String method; see String's documentation for the Pattern call each one is + * equivalent to. + */ +final class DeadlineRegex { + + /** Returned when the call isn't one of these methods. */ + static final Object NOT_HANDLED = new Object(); + + private DeadlineRegex() { + } + + static Object invoke(String s, String methodName, Object[] args) { + if (args == null || args.length == 0 || !(args[0] instanceof String)) { + return NOT_HANDLED; + } + String regex = (String) args[0]; + CharSequence text = new DeadlineText(s); + switch (methodName) { + case "matches": + return args.length == 1 ? Pattern.compile(regex).matcher(text).matches() + : NOT_HANDLED; + case "replaceAll": + return args.length == 2 && args[1] instanceof String + ? Pattern.compile(regex).matcher(text).replaceAll((String) args[1]) + : NOT_HANDLED; + case "replaceFirst": + return args.length == 2 && args[1] instanceof String + ? Pattern.compile(regex).matcher(text).replaceFirst((String) args[1]) + : NOT_HANDLED; + case "split": + if (args.length == 1) { + return Pattern.compile(regex).split(text, 0); + } + return args.length == 2 && args[1] instanceof Integer + ? Pattern.compile(regex).split(text, (Integer) args[1]) + : NOT_HANDLED; + default: + return NOT_HANDLED; + } + } + + /** A string that checks the deadline every few thousand character reads. */ + private static final class DeadlineText implements CharSequence { + + private final String s; + private int reads = 0; + + DeadlineText(String s) { + this.s = s; + } + + @Override + public char charAt(int index) { + if ((++reads & 0xfff) == 0) { + RenderSession.checkDeadline(); + } + return s.charAt(index); + } + + @Override + public int length() { + return s.length(); + } + + @Override + public CharSequence subSequence(int start, int end) { + return s.subSequence(start, end); + } + + @Override + public String toString() { + return s; + } + } +} diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitContext.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitContext.java new file mode 100644 index 0000000000..5c2e07663c --- /dev/null +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitContext.java @@ -0,0 +1,59 @@ +/* + * 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.Map; + +import org.apache.velocity.VelocityContext; + +/** + * The context a weblog template renders against. Every variable read and + * write, and every macro call, checks the render deadline, so a template that + * only sets variables or calls macros, without output or method calls, still + * stops in time; a string stored in a variable may be no longer than the + * output limit. + */ +class RenderLimitContext extends VelocityContext { + + RenderLimitContext(Map model) { + super(model); + } + + @Override + public Object internalGet(String key) { + RenderSession.checkDeadline(); + return super.internalGet(key); + } + + @Override + public Object internalPut(String key, Object value) { + RenderSession.checkDeadline(); + if (value instanceof CharSequence) { + RenderSession.checkLength(((CharSequence) value).length()); + } + return super.internalPut(key, value); + } + + @Override + public void pushCurrentMacroName(String name) { + RenderSession.checkDeadline(); + super.pushCurrentMacroName(name); + } +} diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitParser.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitParser.java new file mode 100644 index 0000000000..4f64ea08f4 --- /dev/null +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitParser.java @@ -0,0 +1,233 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.roller.weblogger.ui.rendering.velocity; + +import java.io.IOException; +import java.io.Reader; +import java.io.Writer; +import java.lang.reflect.Field; + +import org.apache.velocity.Template; +import org.apache.velocity.context.InternalContextAdapter; +import org.apache.velocity.runtime.RuntimeServices; +import org.apache.velocity.runtime.parser.ParseException; +import org.apache.velocity.runtime.parser.Parser; +import org.apache.velocity.runtime.parser.StandardParser; +import org.apache.velocity.runtime.parser.node.ASTAddNode; +import org.apache.velocity.runtime.parser.node.ASTBlock; +import org.apache.velocity.runtime.parser.node.ASTprocess; +import org.apache.velocity.runtime.parser.node.Node; +import org.apache.velocity.runtime.parser.node.SimpleNode; + +/** + * Velocity builds some strings in memory rather than in the output: string + * literals such as "$a$b", the + operator, and #define blocks or macro bodies + * used as strings. This parser, set as parser.class in velocity.properties, + * swaps the nodes that do so for ones that stop at the output limit while the + * string is built: + * + *

+ * + *

The nodes keep no state of their own between renders, so a parsed + * template is still safe to share between threads. + */ +public class RenderLimitParser extends StandardParser { + + public RenderLimitParser(RuntimeServices rs) { + super(rs); + } + + @Override + public SimpleNode parse(Reader reader, Template template) throws ParseException { + SimpleNode root = super.parse(reader, template); + if (root == null) { + return null; + } + SimpleNode limited = root.getClass() == ASTprocess.class + ? new LimitedProcess(this, (ASTprocess) root) : root; + limitChildren(limited); + return limited; + } + + private void limitChildren(Node node) { + for (int i = 0; i < node.jjtGetNumChildren(); i++) { + Node child = node.jjtGetChild(i); + Node limited = child; + if (child.getClass() == ASTBlock.class) { + limited = new LimitedBlock(this, (ASTBlock) child); + } else if (child.getClass() == ASTAddNode.class) { + limited = new LimitedAddNode(this, (ASTAddNode) child); + } + if (limited != child) { + node.jjtAddChild(limited, i); + limited.jjtSetParent(node); + } + limitChildren(limited); + } + } + + /** Moves the children and source position of a parsed node to its replacement. */ + private static void moveChildren(SimpleNode from, SimpleNode to) { + to.setFirstToken(from.getFirstToken()); + to.setInfo(from.getInfo()); + if (from.isInvalid()) { + to.setInvalid(); + } + for (int i = 0; i < from.jjtGetNumChildren(); i++) { + Node child = from.jjtGetChild(i); + to.jjtAddChild(child, i); + child.jjtSetParent(to); + } + } + + /** + * @return the writer to render into: the same writer when it already + * counts toward the output limit, otherwise one that counts what + * this render writes into it + */ + static Writer limited(Writer writer) { + if (writer instanceof RenderLimitWriter || writer instanceof CountingWriter + || RenderSession.current() == null) { + return writer; + } + return new CountingWriter(writer); + } + + /** Counts what one render writes into a buffer such as a string literal's. */ + static final class CountingWriter extends Writer { + + private final Writer out; + private long written = 0; + + CountingWriter(Writer out) { + this.out = out; + } + + private void count(long len) { + written += len; + RenderSession.checkLength(written); + RenderSession.checkDeadline(); + } + + @Override + public void write(int c) throws IOException { + count(1); + out.write(c); + } + + @Override + public void write(char[] cbuf, int off, int len) throws IOException { + count(len); + out.write(cbuf, off, len); + } + + @Override + public void write(String str, int off, int len) throws IOException { + count(len); + out.write(str, off, len); + } + + @Override + public void flush() throws IOException { + out.flush(); + } + + @Override + public void close() throws IOException { + out.close(); + } + } + + static final class LimitedProcess extends ASTprocess { + + LimitedProcess(Parser parser, ASTprocess from) { + super(parser, from.getType()); + moveChildren(from, this); + this.last = from.getLastToken(); + } + + @Override + public boolean render(InternalContextAdapter context, Writer writer) throws IOException { + return super.render(context, limited(writer)); + } + } + + static final class LimitedBlock extends ASTBlock { + + // ASTBlock has no getter for the whitespace the parser keeps after it + private static final Field MORE_POSTFIX; + + static { + try { + MORE_POSTFIX = ASTBlock.class.getDeclaredField("morePostfix"); + MORE_POSTFIX.setAccessible(true); + } catch (NoSuchFieldException ex) { + throw new IllegalStateException( + "this Velocity version's ASTBlock has no morePostfix field", ex); + } + } + + LimitedBlock(Parser parser, ASTBlock from) { + super(parser, from.getType()); + moveChildren(from, this); + this.last = from.getLastToken(); + setPrefix(from.getPrefix()); + setPostfix(from.getPostfix()); + endsWithNewline = from.endsWithNewline; + try { + setMorePostfix((String) MORE_POSTFIX.get(from)); + } catch (IllegalAccessException ex) { + throw new IllegalStateException(ex); + } + } + + @Override + public boolean render(InternalContextAdapter context, Writer writer) throws IOException { + return super.render(context, limited(writer)); + } + } + + static final class LimitedAddNode extends ASTAddNode { + + LimitedAddNode(Parser parser, ASTAddNode from) { + super(parser, from.getType()); + moveChildren(from, this); + this.last = from.getLastToken(); + } + + @Override + protected Object handleSpecial(Object left, Object right, InternalContextAdapter context) { + if (left instanceof CharSequence && right instanceof CharSequence) { + RenderSession.checkLength((long) ((CharSequence) left).length() + + ((CharSequence) right).length()); + } + Object result = super.handleSpecial(left, right, context); + if (result instanceof CharSequence) { + RenderSession.checkLength(((CharSequence) result).length()); + } + return result; + } + } +} diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitUberspector.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitUberspector.java index 33402a1cdc..2f4a7ecaa2 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitUberspector.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitUberspector.java @@ -36,7 +36,8 @@ * a string a call returns may be no longer than the output limit, a call that * could build a longer string is stopped before it runs, and string methods * whose result can't be bounded from the call (String.repeat, String.format - * and others; see StringGrowth) are not offered. + * and others; see StringGrowth) are not offered. Regular expressions given to + * String methods check the deadline as they run; see DeadlineRegex. */ public class RenderLimitUberspector extends AbstractChainableUberspector { @@ -90,6 +91,12 @@ public Object invoke(Object o, Object[] params) if (RenderSession.current() != null) { RenderSession.checkLength(StringGrowth.maxResultLength( o, method.getMethodName(), params)); + if (o instanceof String) { + Object result = DeadlineRegex.invoke((String) o, method.getMethodName(), params); + if (result != DeadlineRegex.NOT_HANDLED) { + return checked(result); + } + } } return checked(method.invoke(o, params)); } 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 9b25857b33..0d6999924d 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 @@ -30,6 +30,7 @@ import org.apache.roller.weblogger.pojos.TemplateRendition.RenditionType; import org.apache.roller.weblogger.pojos.WeblogTemplate; import org.apache.velocity.exception.ResourceNotFoundException; +import org.apache.velocity.exception.VelocityException; import org.apache.velocity.runtime.resource.Resource; import org.apache.velocity.runtime.resource.loader.ResourceLoader; import org.apache.velocity.util.ExtProperties; @@ -53,6 +54,11 @@ public void init(ExtProperties configuration) { if (logger.isDebugEnabled()) { logger.debug(configuration); } + // see inRenderScope() + if (configuration.getBoolean("cache", false)) { + throw new VelocityException("resource.loader.roller.cache must be false," + + " so that each weblog renders only its own templates"); + } } /** @@ -122,7 +128,8 @@ public Reader getResourceReader(String name, String encoding) { * 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. + * 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(); 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 c0686578ed..384392a2b1 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 @@ -131,8 +131,8 @@ public void render(Map model, Writer out) long startTime = System.currentTimeMillis(); - // convert model to Velocity Context - Context ctx = new VelocityContext(model); + // convert model to Velocity Context; see RenderLimitContext + Context ctx = new RenderLimitContext(model); if (velocityDecorator != null) { diff --git a/app/src/main/webapp/WEB-INF/velocity.properties b/app/src/main/webapp/WEB-INF/velocity.properties index 0ac1331022..dd7e9f3d09 100644 --- a/app/src/main/webapp/WEB-INF/velocity.properties +++ b/app/src/main/webapp/WEB-INF/velocity.properties @@ -82,6 +82,9 @@ default.contentType=text/html; charset=utf-8 # inserted value is checked against the output limit. The limits themselves # are rendering.maxOutputChars and rendering.maxRenderSeconds in # roller.properties. +# swaps in nodes that stop string literals, + and blocks used as strings at +# the output limit; see RenderLimitParser +parser.class=org.apache.roller.weblogger.ui.rendering.velocity.RenderLimitParser introspector.uberspect.class=org.apache.velocity.util.introspection.SecureUberspector,org.apache.roller.weblogger.ui.rendering.velocity.RenderLimitUberspector runtime.custom_directives=org.apache.roller.weblogger.ui.rendering.velocity.RollerForeach directive.foreach.max_loops=100000 diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegexTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegexTest.java new file mode 100644 index 0000000000..200fd548ff --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegexTest.java @@ -0,0 +1,64 @@ +/* + * 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.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; + +/** DeadlineRegex has to give the same results as the String methods it stands in for. */ +class DeadlineRegexTest { + + private static final String[] TEXTS = {"", "a", "a,b,,c,,", "Hello, World", " x y "}; + private static final String[] PATTERNS = {"", ",", "\\s+", "l+", "(?=(.*))", "(.)", "\\b", "$"}; + private static final String[] REPLACEMENTS = {"", "x", "$0", "[$1]", "\\$"}; + + @Test + void givesTheSameResultsAsString() { + for (String s : TEXTS) { + for (String p : PATTERNS) { + assertEquals(s.matches(p), DeadlineRegex.invoke(s, "matches", new Object[] {p})); + assertArrayEquals(s.split(p), + (String[]) DeadlineRegex.invoke(s, "split", new Object[] {p}), s + " / " + p); + for (int limit : new int[] {-1, 0, 1, 2}) { + assertArrayEquals(s.split(p, limit), + (String[]) DeadlineRegex.invoke(s, "split", new Object[] {p, limit})); + } + for (String r : REPLACEMENTS) { + if (r.contains("$1") && !p.contains("(")) { + continue; // no such group: the call throws + } + assertEquals(s.replaceAll(p, r), + DeadlineRegex.invoke(s, "replaceAll", new Object[] {p, r})); + assertEquals(s.replaceFirst(p, r), + DeadlineRegex.invoke(s, "replaceFirst", new Object[] {p, r})); + } + } + } + } + + @Test + void leavesOtherCallsToString() { + assertSame(DeadlineRegex.NOT_HANDLED, DeadlineRegex.invoke("a", "replace", new Object[] {"a", "b"})); + assertSame(DeadlineRegex.NOT_HANDLED, DeadlineRegex.invoke("a", "split", new Object[] {'a'})); + } +} 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 index 244ab93e46..e28483aeec 100644 --- 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 @@ -247,4 +247,87 @@ public void ordinaryStringCallsStillWork() throws Exception { + "[hello, world][World][Hello, World]" + "[Hello,_World]", outcome.out.getHead()); } + + @Test + public void ordinaryLiteralsSumsBlocksAndExpressionsStillWork() throws Exception { + Outcome outcome = render("limits-ordinary-literals.vm", + "#set($a = 'x')#set($b = \"[$a$a]\")#set($c = $a + $b + 1)" + + "#define($d)<#if($a)$a#end>#end#set($e = $d + '')" + + "#macro(wrap)($bodyContent)#end" + + "$b|$c|$d|$e|#@wrap()$a#end|$a.matches('x')|$c.split('\\[').size()" + + "|$c.replaceAll('[x]', 'y')"); + assertEquals(null, outcome.failure); + assertEquals("[xx]|x[xx]1|||(x)|true|2|y[yy]1", outcome.out.getHead()); + } + + /** A string of 5,242,880 digits, half the output limit. */ + private static final String FIVE_MILLION_DIGITS = "#set($s = '0123456789')" + + "#foreach($i in [1..19])#set($s = \"$s$s\")#end"; + + /** About 30 million characters of text, from loops that insert nothing. */ + private static final String THIRTY_MILLION_CHARS = + "#foreach($i in [1..100000])#foreach($j in [1..30])0123456789#end#end"; + + private static void assertStoppedInMemory(String name, String source) throws Exception { + Outcome outcome = render(name, source); + assertNotNull(outcome.failure, name + " should have failed, but wrote " + + outcome.out.getCount() + " chars"); + assertFalse(reachedTestCeiling(outcome.failure), + "only the test's own ceiling stopped rendering"); + assertTrue(outcome.out.getCount() < 1024, name + " wrote " + outcome.out.getCount()); + } + + @Test + public void aStringDoubledWithPlusStopsAtTheSizeLimit() throws Exception { + assertStoppedInMemory("limits-plus-doubling.vm", "#set($s = '0123456789')" + + "#foreach($i in [1..22])#set($s = $s + $s)#end$s.length()"); + } + + @Test + public void oneLongSumStopsAtTheSizeLimit() throws Exception { + assertStoppedInMemory("limits-plus-sum.vm", FIVE_MILLION_DIGITS + + "#set($t = $s + $s + $s + $s)$t.length()"); + } + + @Test + public void aStringLiteralWithManyReferencesStopsAtTheSizeLimit() throws Exception { + assertStoppedInMemory("limits-literal-refs.vm", FIVE_MILLION_DIGITS + + "#set($t = \"$s$s$s$s\")$t.length()"); + } + + @Test + public void loopsInsideAStringLiteralStopAtTheSizeLimit() throws Exception { + assertStoppedInMemory("limits-literal-loops.vm", + "#set($t = \"" + THIRTY_MILLION_CHARS + "\")$t.length()"); + } + + @Test + public void aDefinedBlockTurnedIntoAStringStopsAtTheSizeLimit() throws Exception { + assertStoppedInMemory("limits-define.vm", + "#define($b)" + THIRTY_MILLION_CHARS + "#end#set($t = $b + '')$t.length()"); + } + + @Test + public void macroRecursionThatWritesNothingStopsAtTheDeadline() throws Exception { + long start = System.nanoTime(); + // four calls a level, 13 levels deep: about 90 million calls + String call = "#set($e = $d - 1)#spin($e)"; + Outcome outcome = render("limits-macro-recursion.vm", + "#macro(spin $d)#if($d > 0)" + call + call + call + call + "#end#end" + + "#spin(13)done"); + long seconds = (System.nanoTime() - start) / 1_000_000_000L; + assertNotNull(outcome.failure, "rendering should have failed after " + + seconds + " seconds, but wrote " + outcome.out.getHead()); + assertTrue(seconds < 10, "rendering took " + seconds + " seconds"); + } + + @Test + public void aSlowRegularExpressionStopsAtTheDeadline() throws Exception { + long start = System.nanoTime(); + Outcome outcome = render("limits-regex.vm", + "#set($s = '" + "a".repeat(36) + "')[$s.matches('(.*a){12}b')]"); + long seconds = (System.nanoTime() - start) / 1_000_000_000L; + assertNotNull(outcome.failure, "rendering should have failed"); + assertTrue(seconds < 10, "rendering took " + seconds + " seconds"); + } } 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 index d595e6e361..03b9c9beb2 100644 --- 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 @@ -38,12 +38,15 @@ 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; /** @@ -265,4 +268,20 @@ public void macrosStillReachAcrossAWeblogsOwnTemplates() throws Exception { 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 6a0a7d96b0..7d94fd935e 100644 --- a/app/src/test/resources/WEB-INF/velocity.properties +++ b/app/src/test/resources/WEB-INF/velocity.properties @@ -85,6 +85,9 @@ default.contentType=text/html; charset=utf-8 # inserted value is checked against the output limit. The limits themselves # are rendering.maxOutputChars and rendering.maxRenderSeconds in # roller.properties. +# swaps in nodes that stop string literals, + and blocks used as strings at +# the output limit; see RenderLimitParser +parser.class=org.apache.roller.weblogger.ui.rendering.velocity.RenderLimitParser introspector.uberspect.class=org.apache.velocity.util.introspection.SecureUberspector,org.apache.roller.weblogger.ui.rendering.velocity.RenderLimitUberspector runtime.custom_directives=org.apache.roller.weblogger.ui.rendering.velocity.RollerForeach directive.foreach.max_loops=100000 From 4724f547c7f65e8481f256a5c21ecbca6863d887 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Tue, 17 Nov 2026 20:35:41 -0700 Subject: [PATCH 04/18] Check regex replaces against the output limit as they run, and drop the context checks replaceAll and replaceFirst now check the output limit before each replacement instead of refusing any call whose worst case over the whole string is over the limit, so a replace with group references such as $s.replaceAll('(\d)', '<$1>') on a long string works again. The arguments of the regular expression methods are converted the way Velocity converts them. RenderLimitContext is removed: every block render already writes to the counted output, which checks the deadline, so a macro that writes nothing still stops in time, and strings built by literals and + are now checked where they are built. --- .../ui/rendering/velocity/DeadlineRegex.java | 76 +++++++++++++++---- .../velocity/RenderLimitContext.java | 59 -------------- .../ui/rendering/velocity/StringGrowth.java | 27 +------ .../rendering/velocity/VelocityRenderer.java | 4 +- .../rendering/velocity/DeadlineRegexTest.java | 12 ++- .../rendering/velocity/RenderLimitsTest.java | 28 +++++-- .../rendering/velocity/StringGrowthTest.java | 23 +----- 7 files changed, 101 insertions(+), 128 deletions(-) delete mode 100644 app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitContext.java diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java index a45f0261b2..b40b6baf4c 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java @@ -19,15 +19,17 @@ package org.apache.roller.weblogger.ui.rendering.velocity; +import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Runs the String methods that take a regular expression (matches, * replaceAll, replaceFirst and split) over text that checks the render * deadline as the expression reads it, so a slow expression stops with the - * render instead of holding the thread. Each gives the same result as the - * String method; see String's documentation for the Pattern call each one is - * equivalent to. + * render instead of holding the thread, and replaceAll and replaceFirst stop + * at the output limit as they build the result. Each gives the same result + * as the String method; see String's documentation for the Pattern call each + * one is equivalent to. */ final class DeadlineRegex { @@ -37,36 +39,82 @@ final class DeadlineRegex { private DeadlineRegex() { } + /** + * @return the result of the call, or NOT_HANDLED when it isn't one of + * these methods or its arguments don't fit them + */ static Object invoke(String s, String methodName, Object[] args) { - if (args == null || args.length == 0 || !(args[0] instanceof String)) { + if (args == null || args.length == 0 || args.length > 2 || args[0] == null) { return NOT_HANDLED; } - String regex = (String) args[0]; + // Velocity converts arguments to the method's parameter types after + // this sees them, so convert them the same way here + String regex = args[0].toString(); + Object second = args.length > 1 ? args[1] : null; CharSequence text = new DeadlineText(s); switch (methodName) { case "matches": return args.length == 1 ? Pattern.compile(regex).matcher(text).matches() : NOT_HANDLED; case "replaceAll": - return args.length == 2 && args[1] instanceof String - ? Pattern.compile(regex).matcher(text).replaceAll((String) args[1]) - : NOT_HANDLED; case "replaceFirst": - return args.length == 2 && args[1] instanceof String - ? Pattern.compile(regex).matcher(text).replaceFirst((String) args[1]) - : NOT_HANDLED; + return second == null ? NOT_HANDLED : replace(Pattern.compile(regex).matcher(text), + second.toString(), "replaceAll".equals(methodName)); case "split": if (args.length == 1) { return Pattern.compile(regex).split(text, 0); } - return args.length == 2 && args[1] instanceof Integer - ? Pattern.compile(regex).split(text, (Integer) args[1]) - : NOT_HANDLED; + Integer limit = toInt(second); + return limit == null ? NOT_HANDLED : Pattern.compile(regex).split(text, limit); default: return NOT_HANDLED; } } + private static Integer toInt(Object value) { + if (value instanceof Number) { + return ((Number) value).intValue(); + } + if (value instanceof String) { + try { + return Integer.valueOf(((String) value).trim()); + } catch (NumberFormatException ex) { + return null; + } + } + return null; + } + + /** + * Matcher.replaceAll and replaceFirst, checking before each replacement + * that it can't take the result past the output limit: a replacement adds + * at most its own length plus, for each group reference ($1, ${name}) in + * it, the longest group of that match. + */ + private static String replace(Matcher m, String replacement, boolean all) { + long references = replacement.chars().filter(c -> c == '$').count(); + StringBuilder out = new StringBuilder(); + int previousEnd = 0; + while (m.find()) { + long longestGroup = 0; + for (int g = 0; g <= m.groupCount(); g++) { + if (m.start(g) >= 0) { + longestGroup = Math.max(longestGroup, m.end(g) - m.start(g)); + } + } + RenderSession.checkLength((long) out.length() + (m.start() - previousEnd) + + replacement.length() + references * longestGroup); + m.appendReplacement(out, replacement); + previousEnd = m.end(); + if (!all) { + break; + } + } + m.appendTail(out); + RenderSession.checkLength(out.length()); + return out.toString(); + } + /** A string that checks the deadline every few thousand character reads. */ private static final class DeadlineText implements CharSequence { diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitContext.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitContext.java deleted file mode 100644 index 5c2e07663c..0000000000 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitContext.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * 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.Map; - -import org.apache.velocity.VelocityContext; - -/** - * The context a weblog template renders against. Every variable read and - * write, and every macro call, checks the render deadline, so a template that - * only sets variables or calls macros, without output or method calls, still - * stops in time; a string stored in a variable may be no longer than the - * output limit. - */ -class RenderLimitContext extends VelocityContext { - - RenderLimitContext(Map model) { - super(model); - } - - @Override - public Object internalGet(String key) { - RenderSession.checkDeadline(); - return super.internalGet(key); - } - - @Override - public Object internalPut(String key, Object value) { - RenderSession.checkDeadline(); - if (value instanceof CharSequence) { - RenderSession.checkLength(((CharSequence) value).length()); - } - return super.internalPut(key, value); - } - - @Override - public void pushCurrentMacroName(String name) { - RenderSession.checkDeadline(); - super.pushCurrentMacroName(name); - } -} diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java index d0db017016..8945690736 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java @@ -125,16 +125,9 @@ private static long forString(String s, String methodName, Object[] a) { } return len; case "replaceAll": - case "replaceFirst": { - // each match adds the replacement, and each group reference - // in it ($1, ${name}) can add up to the whole receiver; an - // empty pattern matches len + 1 times - long repl = length(a.length > 1 ? a[1] : null); - long refs = count(a.length > 1 ? a[1] : null, '$'); - long perMatch = add(repl, multiply(refs, len)); - long matches = "replaceAll".equals(methodName) ? len + 1 : 1; - return add(len, multiply(matches, perMatch)); - } + case "replaceFirst": + // DeadlineRegex runs these and checks the limit as it goes + return 0; case "concat": return add(len, length(a.length > 0 ? a[0] : null)); case "toUpperCase": @@ -200,20 +193,6 @@ private static long length(Object value) { return value == null ? 0 : SCALAR_LENGTH; } - private static long count(Object value, char c) { - if (!(value instanceof CharSequence)) { - return 0; - } - CharSequence cs = (CharSequence) value; - long n = 0; - for (int i = 0; i < cs.length(); i++) { - if (cs.charAt(i) == c) { - n++; - } - } - return n; - } - private static long add(long a, long b) { long sum = a + b; return sum < 0 ? Long.MAX_VALUE : sum; diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/VelocityRenderer.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/VelocityRenderer.java index 384392a2b1..c0686578ed 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 @@ -131,8 +131,8 @@ public void render(Map model, Writer out) long startTime = System.currentTimeMillis(); - // convert model to Velocity Context; see RenderLimitContext - Context ctx = new RenderLimitContext(model); + // convert model to Velocity Context + Context ctx = new VelocityContext(model); if (velocityDecorator != null) { diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegexTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegexTest.java index 200fd548ff..44fb6db253 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegexTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegexTest.java @@ -32,6 +32,15 @@ class DeadlineRegexTest { private static final String[] PATTERNS = {"", ",", "\\s+", "l+", "(?=(.*))", "(.)", "\\b", "$"}; private static final String[] REPLACEMENTS = {"", "x", "$0", "[$1]", "\\$"}; + @Test + void convertsArgumentsAsVelocityWould() { + assertArrayEquals("a,b,c".split(",", 2), + (String[]) DeadlineRegex.invoke("a,b,c", "split", new Object[] {",", "2"})); + assertArrayEquals("a,b,c".split(",", 2), + (String[]) DeadlineRegex.invoke("a,b,c", "split", new Object[] {",", 2L})); + assertEquals("a1b1c", DeadlineRegex.invoke("a,b,c", "replaceAll", new Object[] {",", 1})); + } + @Test void givesTheSameResultsAsString() { for (String s : TEXTS) { @@ -59,6 +68,7 @@ void givesTheSameResultsAsString() { @Test void leavesOtherCallsToString() { assertSame(DeadlineRegex.NOT_HANDLED, DeadlineRegex.invoke("a", "replace", new Object[] {"a", "b"})); - assertSame(DeadlineRegex.NOT_HANDLED, DeadlineRegex.invoke("a", "split", new Object[] {'a'})); + assertSame(DeadlineRegex.NOT_HANDLED, DeadlineRegex.invoke("a", "split", new Object[] {"a", true})); + assertSame(DeadlineRegex.NOT_HANDLED, DeadlineRegex.invoke("a", "matches", new Object[] {null})); } } 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 index e28483aeec..d110134665 100644 --- 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 @@ -214,7 +214,9 @@ public void growingStringCallsAreRefusedBeforeTheyRun() throws Exception { for (int i = 0; i < calls.length; i++) { long allocated = allocatedByRender("limits-growing-" + i + ".vm", TEN_THOUSAND_DIGITS + calls[i], context); - assertTrue(allocated < 16L * 1024 * 1024, + // replaceAll builds part of the result before it stops; without + // the checks each of these allocates over 100 MB + assertTrue(allocated < 64L * 1024 * 1024, calls[i] + " allocated " + allocated + " bytes before it was stopped"); } } @@ -323,11 +325,23 @@ public void macroRecursionThatWritesNothingStopsAtTheDeadline() throws Exception @Test public void aSlowRegularExpressionStopsAtTheDeadline() throws Exception { - long start = System.nanoTime(); - Outcome outcome = render("limits-regex.vm", - "#set($s = '" + "a".repeat(36) + "')[$s.matches('(.*a){12}b')]"); - long seconds = (System.nanoTime() - start) / 1_000_000_000L; - assertNotNull(outcome.failure, "rendering should have failed"); - assertTrue(seconds < 10, "rendering took " + seconds + " seconds"); + String[] calls = {"$s.matches('(.*a){12}b')", "$s.split('(.*a){12}b', 2)"}; + for (int i = 0; i < calls.length; i++) { + long start = System.nanoTime(); + Outcome outcome = render("limits-regex-" + i + ".vm", + "#set($s = '" + "a".repeat(36) + "')[" + calls[i] + "]"); + long seconds = (System.nanoTime() - start) / 1_000_000_000L; + assertNotNull(outcome.failure, calls[i] + " should have failed, but wrote " + + outcome.out.getHead() + " in " + seconds + " seconds"); + assertTrue(seconds < 10, calls[i] + " took " + seconds + " seconds"); + } + } + + @Test + public void aRegexReplaceWithGroupsOnALongStringStillWorks() throws Exception { + Outcome outcome = render("limits-regex-groups.vm", TEN_THOUSAND_DIGITS + + "#set($r = $s.replaceAll('(\\d)', '<$1>'))$r.length() $r.substring(0, 9)"); + assertEquals(null, outcome.failure); + assertEquals("30720 <0><1><2>", outcome.out.getHead()); } } diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java index 691484feed..669f7ccc47 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java @@ -35,7 +35,6 @@ class StringGrowthTest { private static final String[] TEXTS = {"", "a", "ab", "aaaa", "Hello, World", "ßßß ff İ"}; - private static final String[] PATTERNS = {"", "a", "l+", "(?=(.*))", "(.)", "\\b", "$"}; private static final String[] REPLACEMENTS = {"", "x", "xyz", "$0", "$1$1", "${g}", "\\$"}; private static void assertBounds(String what, String actual, long bound) { @@ -57,24 +56,6 @@ void literalReplaceIsExact() { } } - @Test - void regexReplaceIsBounded() { - for (String s : TEXTS) { - for (String p : PATTERNS) { - for (String r : REPLACEMENTS) { - if (r.contains("${g}") || (r.contains("$1") && !p.contains("("))) { - continue; // no such group: the call throws - } - Object[] args = {p, r}; - assertBounds("replaceAll", s.replaceAll(p, r), - StringGrowth.maxResultLength(s, "replaceAll", args)); - assertBounds("replaceFirst", s.replaceFirst(p, r), - StringGrowth.maxResultLength(s, "replaceFirst", args)); - } - } - } - } - @Test void caseChangesAndConcatAreBounded() { for (String s : TEXTS) { @@ -112,8 +93,8 @@ void builderGrowthIsBounded() { @Test void hugeBoundsDoNotOverflow() { String s = "0".repeat(100_000); - String r = "$0".repeat(50_000); - long bound = StringGrowth.maxResultLength(s, "replaceAll", new Object[] {"", r}); + String r = "x".repeat(50_000); + long bound = StringGrowth.maxResultLength(s, "replace", new Object[] {"", r}); assertTrue(bound > Integer.MAX_VALUE, "bound was " + bound); } From 0c9c2bce99a7efc9ffa05b6aff89314cf172d01b Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Tue, 17 Nov 2026 21:46:38 -0700 Subject: [PATCH 05/18] Refuse a split that would return more pieces than a template loop can visit --- .../ui/rendering/velocity/DeadlineRegex.java | 27 ++++++++++++++++--- .../rendering/velocity/RenderLimitsTest.java | 23 ++++++++++++++++ 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java index b40b6baf4c..294f79203a 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java @@ -61,16 +61,35 @@ static Object invoke(String s, String methodName, Object[] args) { return second == null ? NOT_HANDLED : replace(Pattern.compile(regex).matcher(text), second.toString(), "replaceAll".equals(methodName)); case "split": - if (args.length == 1) { - return Pattern.compile(regex).split(text, 0); + Integer limit = args.length == 1 ? Integer.valueOf(0) : toInt(second); + if (limit == null) { + return NOT_HANDLED; } - Integer limit = toInt(second); - return limit == null ? NOT_HANDLED : Pattern.compile(regex).split(text, limit); + Pattern pattern = Pattern.compile(regex); + checkPieces(pattern.matcher(text), limit); + return pattern.split(text, limit); default: return NOT_HANDLED; } } + /** No more pieces than a #foreach can visit (directive.foreach.max_loops). */ + static final int MAX_SPLIT_PIECES = 100_000; + + /** + * Counts the pieces a split would return, without allocating them, and + * throws if there are more than MAX_SPLIT_PIECES. + */ + private static void checkPieces(Matcher m, int limit) { + int pieces = 1; + while ((limit <= 0 || pieces < limit) && m.find()) { + if (++pieces > MAX_SPLIT_PIECES) { + throw new RenderLimitException("split produced more than " + + MAX_SPLIT_PIECES + " pieces"); + } + } + } + private static Integer toInt(Object value) { if (value instanceof Number) { return ((Number) value).intValue(); 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 index d110134665..a9cf67c38e 100644 --- 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 @@ -221,6 +221,29 @@ public void growingStringCallsAreRefusedBeforeTheyRun() throws Exception { } } + /** + * A string just under the output limit split into one-character pieces + * would allocate millions of strings before anything checks their size, + * so a split may return no more pieces than a #foreach can visit. + */ + @Test + public void splittingIntoMorePiecesThanALoopCanVisitIsRefused() throws Exception { + // 10,485,760 characters, just under the output limit + String nearTheLimit = TEN_THOUSAND_DIGITS + + "#foreach($i in [1..10])#set($s = \"$s$s\")#end"; + long allocated = allocatedByRender("limits-split.vm", + nearTheLimit + "$s.split('').size()", new HashMap<>()); + // the string itself takes about 40 MB to build; the pieces would add + // over 500 MB + assertTrue(allocated < 160L * 1024 * 1024, + "split allocated " + allocated + " bytes before it was stopped"); + + Outcome ordinary = render("limits-split-ordinary.vm", + TEN_THOUSAND_DIGITS + "$s.split('0').size() $s.split('', 3).size()"); + assertEquals(null, ordinary.failure); + assertEquals("1025 3", ordinary.out.getHead()); + } + /** String.format can pad to any width, so it is not offered. */ @Test public void stringFormatIsNotAvailableToTemplates() throws Exception { From a1ddd1e4dc88ef63eba8531bf2b88e424dafe312 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Wed, 18 Nov 2026 21:09:44 -0700 Subject: [PATCH 06/18] Keep template locations on swapped-in nodes and count only the split pieces that are kept The nodes RenderLimitParser swaps in were built after the parser had let go of the template it was parsing, so they had no template. Velocity asks a node for its template name when it reports a problem, which turned harmless templates such as #set($x = $undefined + 1) and a macro that recurses too deeply into a NullPointerException. The replacement nodes now take the template from the node they replace. A split with the default limit of 0 drops trailing empty pieces, but the piece count included them, so a string ending in many delimiters was refused even though split would have returned few pieces or none. DeadlineRegex now does the split itself in one pass, holding empty pieces back until a piece that isn't empty follows, so trailing empty pieces are neither counted nor allocated and the expression only runs once. The comments above the render limit settings in velocity.properties now describe each setting once. --- .../ui/rendering/velocity/DeadlineRegex.java | 47 ++++++++++++++----- .../rendering/velocity/RenderLimitParser.java | 11 ++++- .../main/webapp/WEB-INF/velocity.properties | 27 +++++++---- .../rendering/velocity/DeadlineRegexTest.java | 26 ++++++++++ .../rendering/velocity/RenderLimitsTest.java | 22 +++++++++ .../resources/WEB-INF/velocity.properties | 35 +++++++++----- 6 files changed, 135 insertions(+), 33 deletions(-) diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java index 294f79203a..fe50c17d02 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java @@ -19,6 +19,8 @@ package org.apache.roller.weblogger.ui.rendering.velocity; +import java.util.ArrayList; +import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -65,9 +67,7 @@ static Object invoke(String s, String methodName, Object[] args) { if (limit == null) { return NOT_HANDLED; } - Pattern pattern = Pattern.compile(regex); - checkPieces(pattern.matcher(text), limit); - return pattern.split(text, limit); + return split(s, Pattern.compile(regex).matcher(text), limit); default: return NOT_HANDLED; } @@ -77,17 +77,42 @@ static Object invoke(String s, String methodName, Object[] args) { static final int MAX_SPLIT_PIECES = 100_000; /** - * Counts the pieces a split would return, without allocating them, and - * throws if there are more than MAX_SPLIT_PIECES. + * Pattern.split, throwing if it would return more than MAX_SPLIT_PIECES. + * With a limit of 0 split drops trailing empty pieces, so those are + * neither counted nor allocated: empty pieces are only added once a piece + * that isn't empty follows them. */ - private static void checkPieces(Matcher m, int limit) { - int pieces = 1; - while ((limit <= 0 || pieces < limit) && m.find()) { - if (++pieces > MAX_SPLIT_PIECES) { - throw new RenderLimitException("split produced more than " - + MAX_SPLIT_PIECES + " pieces"); + private static String[] split(String s, Matcher m, int limit) { + List pieces = new ArrayList<>(); + int heldBack = 0; + int index = 0; + boolean last = false; + while (!last) { + last = limit > 0 && pieces.size() + heldBack == limit - 1 || !m.find(); + if (!last && m.end() == 0) { + // an empty match at the start doesn't make an empty first piece + continue; } + if (last && index == 0) { + // a string with no match is returned whole, even when empty + return new String[] {s}; + } + int end = last ? s.length() : m.start(); + if (limit == 0 && end == index) { + heldBack++; + } else { + if (pieces.size() + heldBack >= MAX_SPLIT_PIECES) { + throw new RenderLimitException("split produced more than " + + MAX_SPLIT_PIECES + " pieces"); + } + for (; heldBack > 0; heldBack--) { + pieces.add(""); + } + pieces.add(s.substring(index, end)); + } + index = last ? end : m.end(); } + return pieces.toArray(new String[0]); } private static Integer toInt(Object value) { diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitParser.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitParser.java index 4f64ea08f4..1e8165a69d 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitParser.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitParser.java @@ -88,7 +88,13 @@ private void limitChildren(Node node) { } } - /** Moves the children and source position of a parsed node to its replacement. */ + /** + * Moves the children and source position of a parsed node to its + * replacement. The replacement's constructor copies the fields only a + * subclass can set: the last token and the template, which the parser no + * longer has once parsing is over and Velocity needs to say where in a + * template something went wrong. + */ private static void moveChildren(SimpleNode from, SimpleNode to) { to.setFirstToken(from.getFirstToken()); to.setInfo(from.getInfo()); @@ -166,6 +172,7 @@ static final class LimitedProcess extends ASTprocess { super(parser, from.getType()); moveChildren(from, this); this.last = from.getLastToken(); + this.template = from.getTemplate(); } @Override @@ -193,6 +200,7 @@ static final class LimitedBlock extends ASTBlock { super(parser, from.getType()); moveChildren(from, this); this.last = from.getLastToken(); + this.template = from.getTemplate(); setPrefix(from.getPrefix()); setPostfix(from.getPostfix()); endsWithNewline = from.endsWithNewline; @@ -215,6 +223,7 @@ static final class LimitedAddNode extends ASTAddNode { super(parser, from.getType()); moveChildren(from, this); this.last = from.getLastToken(); + this.template = from.getTemplate(); } @Override diff --git a/app/src/main/webapp/WEB-INF/velocity.properties b/app/src/main/webapp/WEB-INF/velocity.properties index dd7e9f3d09..56558672e3 100644 --- a/app/src/main/webapp/WEB-INF/velocity.properties +++ b/app/src/main/webapp/WEB-INF/velocity.properties @@ -75,15 +75,24 @@ velocimacro.inline.replace_global=true resource.default_encoding=UTF-8 default.contentType=text/html; charset=utf-8 -# Weblog templates are written by weblog authors, so a render is bounded. -# RenderLimitUberspector, chained after SecureUberspector, checks the render -# deadline on method calls and refuses String.repeat; RollerForeach checks it -# on every #foreach pass, which also stops after max_loops passes; and every -# inserted value is checked against the output limit. The limits themselves -# are rendering.maxOutputChars and rendering.maxRenderSeconds in -# roller.properties. -# swaps in nodes that stop string literals, + and blocks used as strings at -# the output limit; see RenderLimitParser +# Weblog templates are written by weblog authors, so a render is bounded by +# rendering.maxOutputChars and rendering.maxRenderSeconds in +# roller.properties. Each setting below does part of that: +# - parser.class: RenderLimitParser swaps in nodes that stop string literals, +# + and blocks used as strings at the output limit as they are built. +# - introspector.uberspect.class: RenderLimitUberspector, chained after +# SecureUberspector, checks the deadline on every method call and property +# read, stops a call that returns or could build a string longer than the +# output limit, and runs regular expressions given to String methods under +# the deadline. It does not offer the methods whose result can't be bounded +# from the call: repeat, format, formatted, join and indent on String, any +# other String method returning a string that StringGrowth doesn't know, +# and repeat on StringBuilder and StringBuffer. +# - runtime.custom_directives: RollerForeach checks the deadline on every +# #foreach pass. +# - directive.foreach.max_loops: a #foreach stops after this many passes. +# - event_handler.reference_insertion.class: RenderLimitInsertionHandler +# checks the deadline, and each inserted value against the output limit. parser.class=org.apache.roller.weblogger.ui.rendering.velocity.RenderLimitParser introspector.uberspect.class=org.apache.velocity.util.introspection.SecureUberspector,org.apache.roller.weblogger.ui.rendering.velocity.RenderLimitUberspector runtime.custom_directives=org.apache.roller.weblogger.ui.rendering.velocity.RollerForeach diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegexTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegexTest.java index 44fb6db253..195485400d 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegexTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegexTest.java @@ -24,6 +24,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; /** DeadlineRegex has to give the same results as the String methods it stands in for. */ class DeadlineRegexTest { @@ -71,4 +72,29 @@ void leavesOtherCallsToString() { assertSame(DeadlineRegex.NOT_HANDLED, DeadlineRegex.invoke("a", "split", new Object[] {"a", true})); assertSame(DeadlineRegex.NOT_HANDLED, DeadlineRegex.invoke("a", "matches", new Object[] {null})); } + + /** Only the pieces split returns count: it drops trailing empty ones. */ + @Test + void trailingEmptyPiecesDoNotCountTowardTheLimit() { + int max = DeadlineRegex.MAX_SPLIT_PIECES; + String commas = ",".repeat(max + 50_000); + assertArrayEquals(commas.split(","), + (String[]) DeadlineRegex.invoke(commas, "split", new Object[] {","})); + + String atTheLimit = "a,".repeat(max) + commas; + assertEquals(max, + ((String[]) DeadlineRegex.invoke(atTheLimit, "split", new Object[] {","})).length); + // empty pieces before a piece that is kept are returned, so they count + assertEquals(max, + ((String[]) DeadlineRegex.invoke(",".repeat(max - 1) + "a,,", "split", + new Object[] {","})).length); + + assertThrows(RenderLimitException.class, + () -> DeadlineRegex.invoke("a," + atTheLimit, "split", new Object[] {","})); + assertThrows(RenderLimitException.class, + () -> DeadlineRegex.invoke(",".repeat(max) + "a", "split", new Object[] {","})); + // a negative limit keeps the trailing empty pieces + assertThrows(RenderLimitException.class, + () -> DeadlineRegex.invoke(commas, "split", new Object[] {",", -1})); + } } 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 index a9cf67c38e..2f70b1a39e 100644 --- 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 @@ -367,4 +367,26 @@ public void aRegexReplaceWithGroupsOnALongStringStillWorks() throws Exception { assertEquals(null, outcome.failure); assertEquals("30720 <0><1><2>", outcome.out.getHead()); } + + /** + * Velocity asks a node for its template's name to say where something + * went wrong, so the nodes the parser swaps in have to know it too. + */ + @Test + public void arithmeticOnAnUndefinedReferenceStillRenders() throws Exception { + Outcome outcome = render("limits-undefined-sum.vm", + "#set($x = $undefined + 1)ok"); + assertEquals(null, outcome.failure); + assertEquals("ok", outcome.out.getHead()); + } + + @Test + public void endlessMacroRecursionStopsAtTheDepthLimit() throws Exception { + Outcome outcome = render("limits-macro-depth.vm", "#macro(r)#r()#end#r()"); + // Velocity's own error for a macro that calls itself too deeply gets + // the renderer's error page + assertEquals(null, outcome.failure); + assertTrue(outcome.out.getHead().contains(""), + "rendering wrote " + outcome.out.getHead()); + } } diff --git a/app/src/test/resources/WEB-INF/velocity.properties b/app/src/test/resources/WEB-INF/velocity.properties index 7d94fd935e..a2241fac0c 100644 --- a/app/src/test/resources/WEB-INF/velocity.properties +++ b/app/src/test/resources/WEB-INF/velocity.properties @@ -75,21 +75,32 @@ velocimacro.inline.replace_global=true resource.default_encoding=UTF-8 default.contentType=text/html; charset=utf-8 -# Weblog templates render under SecureUberspector, which governs method access -# rather than resource resolution, so the include directives are confined -# separately. Keep this aligned with /WEB-INF/velocity.properties. -# Weblog templates are written by weblog authors, so a render is bounded. -# RenderLimitUberspector, chained after SecureUberspector, checks the render -# deadline on method calls and refuses String.repeat; RollerForeach checks it -# on every #foreach pass, which also stops after max_loops passes; and every -# inserted value is checked against the output limit. The limits themselves -# are rendering.maxOutputChars and rendering.maxRenderSeconds in -# roller.properties. -# swaps in nodes that stop string literals, + and blocks used as strings at -# the output limit; see RenderLimitParser +# Keep these settings aligned with /WEB-INF/velocity.properties. +# +# Weblog templates are written by weblog authors, so a render is bounded by +# rendering.maxOutputChars and rendering.maxRenderSeconds in +# roller.properties. Each setting below does part of that: +# - parser.class: RenderLimitParser swaps in nodes that stop string literals, +# + and blocks used as strings at the output limit as they are built. +# - introspector.uberspect.class: RenderLimitUberspector, chained after +# SecureUberspector, checks the deadline on every method call and property +# read, stops a call that returns or could build a string longer than the +# output limit, and runs regular expressions given to String methods under +# the deadline. It does not offer the methods whose result can't be bounded +# from the call: repeat, format, formatted, join and indent on String, any +# other String method returning a string that StringGrowth doesn't know, +# and repeat on StringBuilder and StringBuffer. +# - runtime.custom_directives: RollerForeach checks the deadline on every +# #foreach pass. +# - directive.foreach.max_loops: a #foreach stops after this many passes. +# - event_handler.reference_insertion.class: RenderLimitInsertionHandler +# checks the deadline, and each inserted value against the output limit. parser.class=org.apache.roller.weblogger.ui.rendering.velocity.RenderLimitParser introspector.uberspect.class=org.apache.velocity.util.introspection.SecureUberspector,org.apache.roller.weblogger.ui.rendering.velocity.RenderLimitUberspector runtime.custom_directives=org.apache.roller.weblogger.ui.rendering.velocity.RollerForeach directive.foreach.max_loops=100000 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 From be943d9f6808f58d5b6cbf425e3b4c041b1603cf Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Thu, 19 Nov 2026 17:48:26 -0700 Subject: [PATCH 07/18] Bound expanding $utils calls before they run and stop over-counting case changes The pre-call output bound covered $utils.replace only, so $utils.escapeHTML, escapeXML, escapeJavaScript, encode, hexEncode, autoformat and the other String-returning $utils methods could build a result many times the output limit before the length check ran. StringGrowth now bounds each of them before the call by counting only the characters that method can expand, and refuses a $utils method added later that returns a string until it is listed. The case-change bound was three times the length, which refused toUpperCase on a large ASCII string whose result fits the limit. It now adds two characters only for each character outside ASCII. DeadlineRegex also checks the text after the last replacement against the limit before appendTail copies it, instead of after. --- .../ui/rendering/velocity/DeadlineRegex.java | 12 +- .../ui/rendering/velocity/StringGrowth.java | 188 +++++++++++++++++- .../rendering/velocity/DeadlineRegexTest.java | 32 +++ .../rendering/velocity/RenderLimitsTest.java | 47 +++++ .../rendering/velocity/StringGrowthTest.java | 166 +++++++++++++++- 5 files changed, 427 insertions(+), 18 deletions(-) diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java index fe50c17d02..10acbd410b 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java @@ -130,10 +130,11 @@ private static Integer toInt(Object value) { } /** - * Matcher.replaceAll and replaceFirst, checking before each replacement - * that it can't take the result past the output limit: a replacement adds - * at most its own length plus, for each group reference ($1, ${name}) in - * it, the longest group of that match. + * Matcher.replaceAll and replaceFirst, checking before each replacement, + * and before the text after the last one, that it can't take the result + * past the output limit: a replacement adds at most its own length plus, + * for each group reference ($1, ${name}) in it, the longest group of that + * match. */ private static String replace(Matcher m, String replacement, boolean all) { long references = replacement.chars().filter(c -> c == '$').count(); @@ -154,8 +155,9 @@ private static String replace(Matcher m, String replacement, boolean all) { break; } } + // the text after the last replacement is copied as it is + RenderSession.checkLength((long) out.length() + (m.regionEnd() - previousEnd)); m.appendTail(out); - RenderSession.checkLength(out.length()); return out.toString(); } diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java index 8945690736..a1febcf07e 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java @@ -20,14 +20,19 @@ package org.apache.roller.weblogger.ui.rendering.velocity; import java.util.Set; +import java.util.function.IntPredicate; +import java.util.regex.Matcher; +import org.apache.roller.util.RegexUtil; import org.apache.roller.weblogger.ui.rendering.model.UtilitiesModel; /** * Some string methods build a result much longer than their receiver and * arguments, so checking the result's length after the call is too late. This * works out, before a call from a template runs, the longest string it can - * build, and names the methods whose result can't be bounded that way. + * build, and names the methods whose result can't be bounded that way. The + * same goes for the $utils methods (UtilitiesModel) that escape, encode or + * add to text. * *

Methods are matched by name so that methods added in later Java versions * (String.indent, String.formatted, StringBuilder.repeat) are covered when @@ -48,12 +53,28 @@ final class StringGrowth { /** StringBuilder and StringBuffer methods that are not offered to templates. */ private static final Set REFUSED_BUILDER_METHODS = Set.of("repeat"); + /** + * UtilitiesModel methods that return a string no longer than an argument, + * or a short one of fixed length. + */ + private static final Set NON_GROWING_UTILITIES_METHODS = Set.of( + "getModelName", "toString", "formatIso8601Date", "formatIso8601Day", + "formatRfc822Date", "format8charsDate", "left", "unescapeHTML", + "unescapeXML", "unescapeJavaScript", "removeHTML", "decode"); + /** Characters a number, boolean or other value appended to a builder may take. */ private static final long SCALAR_LENGTH = 32; - /** Most characters toUpperCase or toLowerCase makes of one character. */ + /** + * Most characters toUpperCase or toLowerCase makes of one character. Only + * characters outside ASCII grow (the Lithuanian lower case of an ASCII I + * gains a dot only before an accent, which is outside ASCII). + */ private static final long CASE_GROWTH = 3; + /** Most characters a pattern letter of a date format writes, with room to spare. */ + private static final long DATE_LETTER_LENGTH = 64; + private StringGrowth() { } @@ -74,6 +95,12 @@ static boolean isRefused(Object receiver, String methodName, Class returnType if (receiver instanceof StringBuilder || receiver instanceof StringBuffer) { return REFUSED_BUILDER_METHODS.contains(methodName); } + if (receiver instanceof UtilitiesModel) { + // a method added later is refused until it is bounded here + return returnType != null && CharSequence.class.isAssignableFrom(returnType) + && !NON_GROWING_UTILITIES_METHODS.contains(methodName) + && !isBoundedUtilitiesMethod(methodName); + } return false; } @@ -91,6 +118,30 @@ private static boolean isBoundedStringMethod(String methodName) { } } + private static boolean isBoundedUtilitiesMethod(String methodName) { + switch (methodName) { + case "replace": + case "toUpperCase": + case "escapeHTML": + case "transformToHTMLSubset": + case "escapeXML": + case "escapeJavaScript": + case "encode": + case "hexEncode": + case "autoformat": + case "addNofollow": + case "encodeEmail": + case "truncate": + case "truncateNicely": + case "truncateText": + case "toBase64": + case "formatDate": + return true; + default: + return false; + } + } + /** * @return the most characters the call can put in one string, or 0 when * it doesn't build a string longer than its receiver or arguments @@ -103,17 +154,132 @@ static long maxResultLength(Object receiver, String methodName, Object[] args) { if (receiver instanceof StringBuilder || receiver instanceof StringBuffer) { return forBuilder((CharSequence) receiver, methodName, a); } - if (receiver instanceof UtilitiesModel && "replace".equals(methodName) - && a.length >= 3 && a[0] instanceof String) { - long maxCount = a.length > 3 && a[3] instanceof Number - ? ((Number) a[3]).longValue() : -1; - if (!(a[1] instanceof String) || ((String) a[1]).isEmpty()) { - // StringUtils.replace leaves the text alone for an empty target + if (receiver instanceof UtilitiesModel) { + return forUtilities(methodName, a); + } + return 0; + } + + private static long forUtilities(String methodName, Object[] a) { + // Velocity converts arguments to the method's parameter types after + // this sees them, so a number passed for a string is counted as one + CharSequence s = a.length > 0 ? text(a[0]) : null; + switch (methodName) { + case "replace": { + if (a.length < 3 || s == null) { + return 0; + } + long maxCount = a.length > 3 && a[3] instanceof Number + ? ((Number) a[3]).longValue() : -1; + CharSequence target = text(a[1]); + if (target == null || target.length() == 0) { + // StringUtils.replace leaves the text alone for an empty target + return 0; + } + return literalReplace(s.toString(), target.toString(), length(a[2]), maxCount); + } + case "toUpperCase": + return caseChange(s); + case "escapeHTML": + case "transformToHTMLSubset": + // an entity is at most ten characters (ϑ); + // transformToHTMLSubset only shrinks text apart from the link + // addresses it escapes the same way + return grown(s, 10, c -> c > 0x7e || c == '&' || c == '<' || c == '>' + || c == '"'); + case "escapeXML": + // at most six characters (" or Ÿ) + return grown(s, 6, c -> c < 0x20 || c > 0x7e || c == '&' || c == '<' + || c == '>' || c == '"' || c == '\''); + case "escapeJavaScript": + // at most six characters (\u00e9) + return grown(s, 6, c -> c < 0x20 || c > 0x7e || c == '\'' || c == '"' + || c == '\\' || c == '/'); + case "encode": + // up to three UTF-8 bytes of %XX each; a space becomes '+' + return grown(s, 9, c -> !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' + || c >= '0' && c <= '9' || c == '.' || c == '-' || c == '*' + || c == '_' || c == ' ')); + case "hexEncode": + // every UTF-8 byte becomes %XX + return add(multiply(3, s == null ? 0 : s.length()), + multiply(6, count(s, c -> c >= 0x80))); + case "autoformat": + return grown(s, "
".length(), c -> c == '\n'); + case "addNofollow": + // only a link that already has rel="nofollow" gets another + return s == null ? 0 : add(s.length(), multiply(" rel=\"nofollow\"".length(), + occurrences(s.toString(), "rel=\"nofollow\""))); + case "encodeEmail": + return encodedEmail(s); + case "truncate": + case "truncateNicely": + case "truncateText": + return add(length(s), length(a.length > 3 ? a[3] : null)); + case "toBase64": + return a.length > 0 && a[0] instanceof byte[] + ? multiply(4, (((byte[]) a[0]).length + 2) / 3) : 0; + case "formatDate": { + CharSequence fmt = a.length > 1 ? text(a[1]) : null; + return grown(fmt, DATE_LETTER_LENGTH, + c -> c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'); + } + default: return 0; + } + } + + /** + * RegexUtil.encodeEmail hex encodes each mailto address, tripling it, and + * then turns the '@' and a '.' of each address into -AT- and -DOT-. + */ + private static long encodedEmail(CharSequence s) { + if (s == null) { + return 0; + } + long mailtoChars = 0; + Matcher m = RegexUtil.MAILTO_PATTERN.matcher(s); + while (m.find()) { + mailtoChars += m.end(1) - m.start(1); + } + long perAt = "-AT-".length() - 1 + "-DOT-".length() - 1; + return add(add(s.length(), multiply(2, mailtoChars)), + multiply(perAt, count(s, c -> c == '@'))); + } + + /** Length of a case change of s. */ + private static long caseChange(CharSequence s) { + return grown(s, CASE_GROWTH, c -> c >= 0x80); + } + + /** Length of s when each character that matches can become up to perChar characters. */ + private static long grown(CharSequence s, long perChar, IntPredicate grows) { + return s == null ? 0 : add(s.length(), multiply(perChar - 1, count(s, grows))); + } + + private static long count(CharSequence s, IntPredicate matches) { + long n = 0; + for (int i = 0; s != null && i < s.length(); i++) { + if (matches.test(s.charAt(i))) { + n++; } - return literalReplace((String) a[0], (String) a[1], length(a[2]), maxCount); } - return 0; + return n; + } + + private static long occurrences(String s, String target) { + long n = 0; + for (int i = s.indexOf(target); i >= 0; i = s.indexOf(target, i + target.length())) { + n++; + } + return n; + } + + private static CharSequence text(Object value) { + if (value == null || value instanceof CharSequence) { + return (CharSequence) value; + } + return value instanceof char[] ? new String((char[]) value) : String.valueOf(value); } private static long forString(String s, String methodName, Object[] a) { @@ -132,7 +298,7 @@ private static long forString(String s, String methodName, Object[] a) { return add(len, length(a.length > 0 ? a[0] : null)); case "toUpperCase": case "toLowerCase": - return multiply(CASE_GROWTH, len); + return caseChange(s); default: return 0; } diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegexTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegexTest.java index 195485400d..4278400870 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegexTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegexTest.java @@ -19,12 +19,15 @@ package org.apache.roller.weblogger.ui.rendering.velocity; +import java.lang.management.ManagementFactory; + import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** DeadlineRegex has to give the same results as the String methods it stands in for. */ class DeadlineRegexTest { @@ -97,4 +100,33 @@ void trailingEmptyPiecesDoNotCountTowardTheLimit() { assertThrows(RenderLimitException.class, () -> DeadlineRegex.invoke(commas, "split", new Object[] {",", -1})); } + + private static long allocatedBytes() { + return ((com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean()) + .getThreadAllocatedBytes(Thread.currentThread().getId()); + } + + /** + * A replacement that takes a string at the output limit one character + * past it has to stop before the rest of the string is copied after it. + */ + @Test + void theTextAfterTheLastReplacementCountsTowardTheLimit() { + RenderSession session = RenderSession.begin(null); + try { + String s = "0".repeat((int) session.getMaxOutputChars()); + for (String method : new String[] {"replaceFirst", "replaceAll"}) { + assertThrows(RenderLimitException.class, + () -> DeadlineRegex.invoke(s, method, new Object[] {"^0", "xx"})); + long before = allocatedBytes(); + assertThrows(RenderLimitException.class, + () -> DeadlineRegex.invoke(s, method, new Object[] {"^0", "xx"})); + long allocated = allocatedBytes() - before; + assertTrue(allocated < 1024 * 1024, + method + " allocated " + allocated + " bytes before it was stopped"); + } + } finally { + session.end(); + } + } } diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitsTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitsTest.java index 2f70b1a39e..50d5b27edb 100644 --- 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 @@ -221,6 +221,53 @@ public void growingStringCallsAreRefusedBeforeTheyRun() throws Exception { } } + /** + * $utils methods that escape or encode text can make each character + * several, so they too have to be refused before they run. Each of these + * on 6,291,456 characters would build at least twice the output limit. + */ + @Test + public void expandingUtilityCallsAreRefusedBeforeTheyRun() throws Exception { + String[] calls = { + "$utils.escapeHTML($s)", + "$utils.escapeXML($s)", + "$utils.escapeJavaScript($s)", + "$utils.encode($s)", + "$utils.hexEncode($s)", + "$utils.autoformat($s)", + }; + Map context = new HashMap<>(); + context.put("utils", new UtilitiesModel()); + String setup = "#set($s = \"<\u00e9\n\")#foreach($i in [1..21])#set($s = \"$s$s\")#end"; + // building the string alone, without the call + String baselineName = "limits-expanding-baseline.vm"; + render(baselineName, setup + "$s.length()", context); + long before = allocatedBytes(); + Outcome baseline = render(baselineName, setup + "$s.length()", context); + long building = allocatedBytes() - before; + assertEquals(null, baseline.failure); + for (int i = 0; i < calls.length; i++) { + long allocated = allocatedByRender("limits-expanding-" + i + ".vm", + setup + calls[i], context) - building; + // without the checks each call allocates at least 25 MB more + assertTrue(allocated < 16L * 1024 * 1024, + calls[i] + " allocated " + allocated + " bytes before it was stopped"); + } + } + + /** A case change of a large ASCII string fits whenever the string does. */ + @Test + public void caseChangesOfALargeAsciiStringStillWork() throws Exception { + Map context = new HashMap<>(); + context.put("utils", new UtilitiesModel()); + Outcome outcome = render("limits-case.vm", FIVE_MILLION_DIGITS + + "$s.toUpperCase().length() $s.toLowerCase().length()" + + " $utils.toUpperCase($s).length() $utils.escapeHTML($s).length()", + context); + assertEquals(null, outcome.failure); + assertEquals("5242880 5242880 5242880 5242880", outcome.out.getHead()); + } + /** * A string just under the output limit split into one-character pieces * would allocate millions of strings before anything checks their size, diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java index 669f7ccc47..c623754454 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java @@ -19,7 +19,16 @@ package org.apache.roller.weblogger.ui.rendering.velocity; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Date; +import java.util.LinkedHashMap; +import java.util.List; import java.util.Locale; +import java.util.Map; +import java.util.function.UnaryOperator; import org.apache.roller.weblogger.ui.rendering.model.UtilitiesModel; import org.junit.jupiter.api.Test; @@ -34,7 +43,8 @@ */ class StringGrowthTest { - private static final String[] TEXTS = {"", "a", "ab", "aaaa", "Hello, World", "ßßß ff İ"}; + private static final String[] TEXTS = {"", "a", "ab", "aaaa", "Hello, World", "ßßß ff İ", + "I\u0300 J\u0301 \u00CC Ii"}; private static final String[] REPLACEMENTS = {"", "x", "xyz", "$0", "$1$1", "${g}", "\\$"}; private static void assertBounds(String what, String actual, long bound) { @@ -59,7 +69,8 @@ void literalReplaceIsExact() { @Test void caseChangesAndConcatAreBounded() { for (String s : TEXTS) { - for (Locale l : new Locale[] {Locale.ROOT, new Locale("tr"), Locale.GERMAN}) { + for (Locale l : new Locale[] {Locale.ROOT, new Locale("tr"), Locale.GERMAN, + new Locale("lt")}) { assertBounds("toUpperCase", s.toUpperCase(l), StringGrowth.maxResultLength(s, "toUpperCase", new Object[] {l})); assertBounds("toLowerCase", s.toLowerCase(l), @@ -70,6 +81,157 @@ void caseChangesAndConcatAreBounded() { } } + /** A case change only adds characters for characters outside ASCII. */ + @Test + void caseChangesOfAsciiAreNotOverestimated() { + String s = "Hello, World 0123456789"; + assertEquals(s.length(), StringGrowth.maxResultLength(s, "toUpperCase", new Object[0])); + assertEquals(s.length(), StringGrowth.maxResultLength(s, "toLowerCase", + new Object[] {Locale.ROOT})); + } + + /** Every char on its own, a surrogate pair, and all of them in one string. */ + private static List everyChar() { + List texts = new ArrayList<>(); + StringBuilder all = new StringBuilder(); + for (int c = 0; c <= 0xFFFF; c++) { + texts.add(String.valueOf((char) c)); + all.append((char) c); + } + texts.add("\uD83D\uDE00"); + texts.add("x\uD83Dy"); + texts.add(all.toString()); + return texts; + } + + /** UtilitiesModel methods that take one string, keyed by name. */ + private static Map> oneStringCalls(UtilitiesModel utils) { + Map> calls = new LinkedHashMap<>(); + calls.put("toUpperCase", utils::toUpperCase); + calls.put("escapeHTML", utils::escapeHTML); + calls.put("unescapeHTML", utils::unescapeHTML); + calls.put("escapeXML", utils::escapeXML); + calls.put("unescapeXML", utils::unescapeXML); + calls.put("escapeJavaScript", utils::escapeJavaScript); + calls.put("unescapeJavaScript", utils::unescapeJavaScript); + calls.put("removeHTML", utils::removeHTML); + calls.put("autoformat", utils::autoformat); + calls.put("hexEncode", utils::hexEncode); + calls.put("encodeEmail", utils::encodeEmail); + calls.put("encode", utils::encode); + calls.put("decode", utils::decode); + calls.put("addNofollow", utils::addNofollow); + calls.put("transformToHTMLSubset", utils::transformToHTMLSubset); + return calls; + } + + private static void assertUtilityBounds(UtilitiesModel utils, String name, String actual, + Object... args) { + long longestArg = 0; + for (Object arg : args) { + longestArg = Math.max(longestArg, arg instanceof CharSequence + ? ((CharSequence) arg).length() : 0); + } + long bound = StringGrowth.maxResultLength(utils, name, args); + assertTrue(actual == null || Math.max(bound, longestArg) >= actual.length(), + name + " produced " + (actual == null ? 0 : actual.length()) + + " chars, bound was " + bound); + } + + @Test + void utilitiesStringCallsAreBounded() { + UtilitiesModel utils = new UtilitiesModel(); + List texts = new ArrayList<>(everyChar()); + texts.add("a<b>b</b><a href='http://x/\u00e9"&'>y</a>" + + "<a href=\"mailto:\u03d1é&\"><br />""); + texts.add(" "); + texts.add("mailto:a.b-c@d.example.org, mailto:a.b-c@d.example.org and x@y.z w@v.u."); + texts.add("\\u0041 \\x41 \\101 %41 %E2%82%AC 😀 ϑ "); + for (Map.Entry> call : oneStringCalls(utils).entrySet()) { + for (String s : texts) { + String actual; + try { + actual = call.getValue().apply(s); + } catch (IllegalArgumentException ex) { + continue; // a malformed escape: the call throws + } + assertUtilityBounds(utils, call.getKey(), actual, s); + } + } + for (String s : TEXTS) { + assertUtilityBounds(utils, "truncateNicely", utils.truncateNicely(s, 1, 2, "..."), + s, 1, 2, "..."); + assertUtilityBounds(utils, "truncateText", utils.truncateText(s, 1, 2, "..."), + s, 1, 2, "..."); + assertUtilityBounds(utils, "truncate", utils.truncate(s, 1, 2, "..."), + s, 1, 2, "..."); + assertUtilityBounds(utils, "left", utils.left(s, 2), s, 2); + assertUtilityBounds(utils, "removeHTML", utils.removeHTML(s, false), s, false); + } + for (int n = 0; n < 10; n++) { + byte[] bytes = new byte[n]; + assertUtilityBounds(utils, "toBase64", utils.toBase64(bytes), bytes, null); + } + } + + @Test + void dateFormatsAreBounded() { + Date date = new Date(1_700_000_000_000L); + StringBuilder all = new StringBuilder(); + for (char c = 'A'; c <= 'z'; c++) { + if (Character.isLetter(c)) { + all.append(c).append(' '); + } + } + for (Locale l : Locale.getAvailableLocales()) { + java.text.SimpleDateFormat f; + try { + f = new java.text.SimpleDateFormat(all.toString(), l); + } catch (IllegalArgumentException ex) { + continue; + } + String actual = f.format(date); + long bound = StringGrowth.maxResultLength(new UtilitiesModel(), "formatDate", + new Object[] {date, all.toString(), null}); + assertTrue(bound >= actual.length(), l + ": " + actual.length() + " > " + bound); + } + } + + /** Plain text gives a bound equal to its length, so large plain text still fits. */ + @Test + void utilitiesCallsOnPlainTextAreNotOverestimated() { + UtilitiesModel utils = new UtilitiesModel(); + String plain = "Hello World 0123456789 abc"; + for (String name : oneStringCalls(utils).keySet()) { + if ("hexEncode".equals(name)) { + continue; // every character becomes at least three + } + assertTrue(StringGrowth.maxResultLength(utils, name, new Object[] {plain}) + <= plain.length(), name); + } + assertEquals(3 * plain.length(), StringGrowth.maxResultLength(utils, "hexEncode", + new Object[] {plain})); + // Velocity converts a number to the string the method takes + assertTrue(StringGrowth.maxResultLength(utils, "escapeHTML", new Object[] {12345}) <= 5); + assertTrue(StringGrowth.maxResultLength(utils, "escapeHTML", + new Object[] {new StringBuilder("<<= "<<<ab".length()); + } + + /** A String-returning method added to UtilitiesModel is refused until it is bounded here. */ + @Test + void everyUtilitiesStringMethodIsKnown() { + UtilitiesModel utils = new UtilitiesModel(); + for (Method m : UtilitiesModel.class.getMethods()) { + if (Modifier.isPublic(m.getModifiers()) + && CharSequence.class.isAssignableFrom(m.getReturnType())) { + assertFalse(StringGrowth.isRefused(utils, m.getName(), m.getReturnType()), + m.getName()); + } + } + assertTrue(StringGrowth.isRefused(utils, "someNewMethod", String.class)); + assertFalse(StringGrowth.isRefused(utils, "someNewMethod", boolean.class)); + } + @Test void utilitiesReplaceIsExact() { UtilitiesModel utils = new UtilitiesModel(); From 526cecb1b49b7e9cf99ebc7221e780412cd5ccab Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Thu, 19 Nov 2026 17:59:54 -0700 Subject: [PATCH 08/18] Count only the characters escapeHTML and escapeXML expand The escapeHTML and escapeXML bounds counted every character outside ASCII as an entity, so large text in Cyrillic, CJK and most other scripts, which those escapers leave alone, was refused. StringGrowth now finds the characters each escaper expands by escaping each char once, and counts only those. --- .../ui/rendering/velocity/StringGrowth.java | 40 ++++++++++++++++--- .../rendering/velocity/StringGrowthTest.java | 6 +++ 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java index a1febcf07e..02d68422cb 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java @@ -19,10 +19,13 @@ package org.apache.roller.weblogger.ui.rendering.velocity; +import java.util.BitSet; import java.util.Set; import java.util.function.IntPredicate; +import java.util.function.UnaryOperator; import java.util.regex.Matcher; +import org.apache.commons.text.StringEscapeUtils; import org.apache.roller.util.RegexUtil; import org.apache.roller.weblogger.ui.rendering.model.UtilitiesModel; @@ -75,6 +78,10 @@ final class StringGrowth { /** Most characters a pattern letter of a date format writes, with room to spare. */ private static final long DATE_LETTER_LENGTH = 64; + /** The characters UtilitiesModel.escapeHTML and escapeXML escape. */ + private static final Escaped HTML_ESCAPED = new Escaped(StringEscapeUtils::escapeHtml4); + private static final Escaped XML_ESCAPED = new Escaped(StringEscapeUtils::escapeXml11); + private StringGrowth() { } @@ -182,15 +189,11 @@ private static long forUtilities(String methodName, Object[] a) { return caseChange(s); case "escapeHTML": case "transformToHTMLSubset": - // an entity is at most ten characters (ϑ); // transformToHTMLSubset only shrinks text apart from the link // addresses it escapes the same way - return grown(s, 10, c -> c > 0x7e || c == '&' || c == '<' || c == '>' - || c == '"'); + return HTML_ESCAPED.length(s); case "escapeXML": - // at most six characters (" or Ÿ) - return grown(s, 6, c -> c < 0x20 || c > 0x7e || c == '&' || c == '<' - || c == '>' || c == '"' || c == '\''); + return XML_ESCAPED.length(s); case "escapeJavaScript": // at most six characters (\u00e9) return grown(s, 6, c -> c < 0x20 || c > 0x7e || c == '\'' || c == '"' @@ -247,6 +250,31 @@ private static long encodedEmail(CharSequence s) { multiply(perAt, count(s, c -> c == '@'))); } + /** + * The characters an escaper turns into more than one, found by escaping + * each one, so that text the escaper leaves alone (most letters outside + * ASCII) isn't counted. + */ + private static final class Escaped { + + private final BitSet grows = new BitSet(Character.MAX_VALUE + 1); + private long longest = 1; + + Escaped(UnaryOperator escape) { + for (int c = 0; c <= Character.MAX_VALUE; c++) { + int length = escape.apply(String.valueOf((char) c)).length(); + if (length > 1) { + grows.set(c); + longest = Math.max(longest, length); + } + } + } + + long length(CharSequence s) { + return grown(s, longest, grows::get); + } + } + /** Length of a case change of s. */ private static long caseChange(CharSequence s) { return grown(s, CASE_GROWTH, c -> c >= 0x80); diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java index c623754454..f1d319c24b 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java @@ -211,6 +211,12 @@ void utilitiesCallsOnPlainTextAreNotOverestimated() { } assertEquals(3 * plain.length(), StringGrowth.maxResultLength(utils, "hexEncode", new Object[] {plain})); + // escapeHTML and escapeXML leave most letters outside ASCII alone + String text = "\u041f\u0440\u0438\u0432\u0435\u0442 \u4f60\u597d \u3053\u3093\u306b\u3061\u306f"; + for (String name : new String[] {"escapeHTML", "escapeXML", "transformToHTMLSubset"}) { + assertEquals(text.length(), StringGrowth.maxResultLength(utils, name, + new Object[] {text}), name); + } // Velocity converts a number to the string the method takes assertTrue(StringGrowth.maxResultLength(utils, "escapeHTML", new Object[] {12345}) <= 5); assertTrue(StringGrowth.maxResultLength(utils, "escapeHTML", From da47cdd03ed36f74fd80c0e5b993d4465d1c7e21 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Fri, 20 Nov 2026 14:24:19 -0700 Subject: [PATCH 09/18] Read stored templates as text instead of encoding and decoding them RollerResourceLoader turned each stored template into bytes in the template encoding and read them back with the platform's default charset, which changes text outside ASCII when the two differ. The template is already a string, so it is now read with a StringReader. --- .../ui/rendering/velocity/RollerResourceLoader.java | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) 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 0d6999924d..89b3ea8c9a 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerResourceLoader.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RollerResourceLoader.java @@ -17,10 +17,8 @@ */ package org.apache.roller.weblogger.ui.rendering.velocity; -import java.io.ByteArrayInputStream; -import java.io.InputStreamReader; import java.io.Reader; -import java.io.UnsupportedEncodingException; +import java.io.StringReader; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -106,13 +104,8 @@ public Reader getResourceReader(String name, String encoding) { if (templateCode != null) { contents = templateCode.getTemplate(); } - return new InputStreamReader(new ByteArrayInputStream(contents.getBytes(encoding))); - - } catch (UnsupportedEncodingException uex) { - // This should never actually happen. We expect UTF-8 in all JRE - // installation. -// logger.error(uex); - throw new RuntimeException(uex); + // the template is already text, so it needs no encoding + return new StringReader(contents); } catch (WebloggerException | ResourceNotFoundException re) { String msg = "RollerResourceLoader Error: " From ca0cc159e47ae78c4fdf745df6cab740a53e9117 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Fri, 20 Nov 2026 14:24:19 -0700 Subject: [PATCH 10/18] Parse templates with many nodes in linear time RenderLimitParser moved each node's children to its replacement from the first to the last, so the child array grew by one on every move. They are now moved last first, and the array is allocated once. --- .../weblogger/ui/rendering/velocity/RenderLimitParser.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitParser.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitParser.java index 1e8165a69d..7b117b806e 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitParser.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitParser.java @@ -101,7 +101,8 @@ private static void moveChildren(SimpleNode from, SimpleNode to) { if (from.isInvalid()) { to.setInvalid(); } - for (int i = 0; i < from.jjtGetNumChildren(); i++) { + // last child first, so the child array is allocated once + for (int i = from.jjtGetNumChildren() - 1; i >= 0; i--) { Node child = from.jjtGetChild(i); to.jjtAddChild(child, i); child.jjtSetParent(to); From d387f4973275d2e08faa872992b679a44ab9b058 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Fri, 20 Nov 2026 14:24:19 -0700 Subject: [PATCH 11/18] Shorten long template error messages in the log and on the error page A template error can quote a value from the template in full, such as a long string passed to a method. The log line and the error page now show the first 1,000 characters, and the log line stays on one line. --- .../rendering/velocity/VelocityRenderer.java | 24 ++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) 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 c0686578ed..744bdc53c2 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/VelocityRenderer.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/VelocityRenderer.java @@ -91,7 +91,7 @@ public VelocityRenderer(Template template, // error page instead so the user knows what was wrong velocityException = ex; log.warn("Error loading [" + template.getId() + "]: " - + ex.getMessage()); + + forLog(ex.getMessage())); // need to lookup error page template velocityTemplate = RollerVelocity.getTemplate("error-page.vm", deviceType); @@ -184,7 +184,7 @@ public void render(Map model, Writer out) // render an error page instead so the user knows what was wrong velocityException = ex; log.warn("Error rendering [" + renderTemplate.getId() + "]: " - + ex.getMessage()); + + forLog(ex.getMessage())); } finally { session.end(); @@ -222,7 +222,7 @@ private String weblogIdFor(Map model) { * for other stored templates; the ids stay in the log */ private String publicMessage(Exception ex) { - String message = ex.getMessage(); + String message = brief(ex.getMessage()); if (message == null) { return null; } @@ -232,6 +232,24 @@ private String publicMessage(Exception ex) { 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) { From 36f66c82f0edf454f2d084ed4b26651be6f9d7e9 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Fri, 20 Nov 2026 14:24:19 -0700 Subject: [PATCH 12/18] Count only the characters a case change or an escape really grows The bounds for toUpperCase and toLowerCase counted every character outside ASCII as tripling, and escapeHTML and escapeXML charged every escaped character with the longest entity, so large Cyrillic or CJK text, or HTML near the limit, was refused although the result would fit. Each character's growth is now looked up in a table built by running the methods on it, in the locales whose case rules differ. The date format test now checks every locale. Its pattern used letters SimpleDateFormat rejects, so it had been checking none. --- .../ui/rendering/velocity/StringGrowth.java | 61 ++++++++++++------- .../rendering/velocity/StringGrowthTest.java | 54 ++++++++++++---- 2 files changed, 82 insertions(+), 33 deletions(-) diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java index 02d68422cb..bc43bf047c 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java @@ -19,7 +19,7 @@ package org.apache.roller.weblogger.ui.rendering.velocity; -import java.util.BitSet; +import java.util.Locale; import java.util.Set; import java.util.function.IntPredicate; import java.util.function.UnaryOperator; @@ -69,18 +69,30 @@ final class StringGrowth { private static final long SCALAR_LENGTH = 32; /** - * Most characters toUpperCase or toLowerCase makes of one character. Only - * characters outside ASCII grow (the Lithuanian lower case of an ASCII I - * gains a dot only before an accent, which is outside ASCII). + * The characters toUpperCase or toLowerCase turn into more than one, in + * any locale. The Lithuanian lower case of I, J and I with ogonek gains a + * dot before an accent, so those count as growing by one. */ - private static final long CASE_GROWTH = 3; + private static final Growth CASE_GROWTH = new Growth(c -> { + String s = String.valueOf((char) c); + int longest = 1; + for (Locale l : new Locale[] {Locale.ROOT, Locale.forLanguageTag("tr"), + Locale.forLanguageTag("az"), Locale.forLanguageTag("lt")}) { + longest = Math.max(longest, Math.max(s.toUpperCase(l).length(), + s.toLowerCase(l).length())); + } + return c == 'I' || c == 'J' || c == '\u012e' ? Math.max(longest, 2) : longest; + }); + + /** Most characters addNofollow is taken to make of one character; see forUtilities. */ + private static final long NOFOLLOW_GROWTH = 9; /** Most characters a pattern letter of a date format writes, with room to spare. */ private static final long DATE_LETTER_LENGTH = 64; - /** The characters UtilitiesModel.escapeHTML and escapeXML escape. */ - private static final Escaped HTML_ESCAPED = new Escaped(StringEscapeUtils::escapeHtml4); - private static final Escaped XML_ESCAPED = new Escaped(StringEscapeUtils::escapeXml11); + /** What UtilitiesModel.escapeHTML and escapeXML make of each character. */ + private static final Growth HTML_ESCAPED = escaped(StringEscapeUtils::escapeHtml4); + private static final Growth XML_ESCAPED = escaped(StringEscapeUtils::escapeXml11); private StringGrowth() { } @@ -251,33 +263,38 @@ private static long encodedEmail(CharSequence s) { } /** - * The characters an escaper turns into more than one, found by escaping - * each one, so that text the escaper leaves alone (most letters outside - * ASCII) isn't counted. + * How many characters each char becomes, found by trying each one, so + * that only the characters that really grow are counted. */ - private static final class Escaped { + private static final class Growth { - private final BitSet grows = new BitSet(Character.MAX_VALUE + 1); - private long longest = 1; + private final byte[] extra = new byte[Character.MAX_VALUE + 1]; - Escaped(UnaryOperator escape) { + Growth(java.util.function.IntUnaryOperator lengthOf) { for (int c = 0; c <= Character.MAX_VALUE; c++) { - int length = escape.apply(String.valueOf((char) c)).length(); - if (length > 1) { - grows.set(c); - longest = Math.max(longest, length); - } + extra[c] = (byte) Math.max(0, lengthOf.applyAsInt(c) - 1); } } long length(CharSequence s) { - return grown(s, longest, grows::get); + if (s == null) { + return 0; + } + long n = s.length(); + for (int i = 0; i < s.length(); i++) { + n += extra[s.charAt(i)]; + } + return n; } } + private static Growth escaped(UnaryOperator escape) { + return new Growth(c -> escape.apply(String.valueOf((char) c)).length()); + } + /** Length of a case change of s. */ private static long caseChange(CharSequence s) { - return grown(s, CASE_GROWTH, c -> c >= 0x80); + return CASE_GROWTH.length(s); } /** Length of s when each character that matches can become up to perChar characters. */ diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java index f1d319c24b..e224f0c360 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java @@ -81,6 +81,42 @@ void caseChangesAndConcatAreBounded() { } } + /** Each character's case change, in the locales whose rules differ, fits its bound. */ + @Test + void caseChangesOfEveryCharAreBounded() { + List texts = everyChar(); + texts.add("I\u0300J\u0301\u012e\u0303"); + for (String s : texts) { + long bound = StringGrowth.maxResultLength(s, "toUpperCase", new Object[0]); + for (Locale l : new Locale[] {Locale.ROOT, new Locale("tr"), new Locale("az"), + new Locale("lt"), Locale.GERMAN}) { + assertBounds("toUpperCase", s.toUpperCase(l), bound); + assertBounds("toLowerCase", s.toLowerCase(l), bound); + } + } + } + + /** Most letters outside ASCII keep their length, so large text in them still fits. */ + @Test + void caseChangesOfTextOutsideAsciiAreNotOverestimated() { + String text = "\u041f\u0440\u0438\u0432\u0435\u0442 \u4f60\u597d \u3053\u3093"; + assertEquals(text.length(), StringGrowth.maxResultLength(text, "toUpperCase", + new Object[0])); + assertEquals(text.length(), StringGrowth.maxResultLength(new UtilitiesModel(), + "toUpperCase", new Object[] {text})); + } + + /** Escaping counts what each character becomes, so the bound is the result's length. */ + @Test + void escapingIsExact() { + UtilitiesModel utils = new UtilitiesModel(); + String html = "

a&b \"c\" d'e \u00e9

"; + assertEquals(utils.escapeHTML(html).length(), + StringGrowth.maxResultLength(utils, "escapeHTML", new Object[] {html})); + assertEquals(utils.escapeXML(html).length(), + StringGrowth.maxResultLength(utils, "escapeXML", new Object[] {html})); + } + /** A case change only adds characters for characters outside ASCII. */ @Test void caseChangesOfAsciiAreNotOverestimated() { @@ -177,24 +213,20 @@ void utilitiesStringCallsAreBounded() { @Test void dateFormatsAreBounded() { Date date = new Date(1_700_000_000_000L); + // every pattern letter SimpleDateFormat knows, each at its longest form StringBuilder all = new StringBuilder(); - for (char c = 'A'; c <= 'z'; c++) { - if (Character.isLetter(c)) { - all.append(c).append(' '); - } + for (char c : "GyYMLwWDdFEuaHkKhmsSzZX".toCharArray()) { + all.append(String.valueOf(c).repeat(c == 'X' ? 3 : 4)).append(' '); } + int checked = 0; for (Locale l : Locale.getAvailableLocales()) { - java.text.SimpleDateFormat f; - try { - f = new java.text.SimpleDateFormat(all.toString(), l); - } catch (IllegalArgumentException ex) { - continue; - } - String actual = f.format(date); + String actual = new java.text.SimpleDateFormat(all.toString(), l).format(date); long bound = StringGrowth.maxResultLength(new UtilitiesModel(), "formatDate", new Object[] {date, all.toString(), null}); assertTrue(bound >= actual.length(), l + ": " + actual.length() + " > " + bound); + checked++; } + assertTrue(checked > 100, "only " + checked + " locales were checked"); } /** Plain text gives a bound equal to its length, so large plain text still fits. */ From ada94bd188fcc0168799ca23f67d68d02a739e4a Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Fri, 20 Nov 2026 14:24:20 -0700 Subject: [PATCH 13/18] Refuse regular expressions that repeat a part that can match an empty string, and count only the groups a replacement uses - An expression with a part that can match empty in more than one way at the same place can try a very large number of ways without reading the text, so the deadline check in DeadlineText never runs. checkPattern refuses a group or assertion that can match empty followed by a quantifier, and a group with two alternatives that can match empty. Pattern itself is used to try whether a part can match empty. - replaceAll and replaceFirst with a null replacement now run under the deadline too, and fail as the String methods do. - A replacement is counted by the lengths of the groups it refers to, so a replace that moves text around in a string near the limit is no longer refused. - String.splitWithDelimiters and lines aren't offered to templates, since DeadlineRegex doesn't run them. - The comments no longer say Velocity converts arguments. It finds no method for a call whose arguments don't fit, so the conversions for those calls are gone. --- .../ui/rendering/velocity/DeadlineRegex.java | 308 ++++++++++++++++-- .../ui/rendering/velocity/StringGrowth.java | 13 +- .../rendering/velocity/DeadlineRegexTest.java | 68 +++- .../rendering/velocity/StringGrowthTest.java | 2 +- 4 files changed, 351 insertions(+), 40 deletions(-) diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java index 10acbd410b..3084bacc33 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java @@ -19,7 +19,9 @@ package org.apache.roller.weblogger.ui.rendering.velocity; +import java.util.ArrayDeque; import java.util.ArrayList; +import java.util.Deque; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -32,6 +34,11 @@ * at the output limit as they build the result. Each gives the same result * as the String method; see String's documentation for the Pattern call each * one is equivalent to. + * + *

An expression can also backtrack without reading the text, when parts + * of it can match an empty string in more than one way, and then the + * deadline is never checked. checkPattern refuses the usual forms of that + * before the expression runs. */ final class DeadlineRegex { @@ -49,25 +56,26 @@ static Object invoke(String s, String methodName, Object[] args) { if (args == null || args.length == 0 || args.length > 2 || args[0] == null) { return NOT_HANDLED; } - // Velocity converts arguments to the method's parameter types after - // this sees them, so convert them the same way here + // the arguments already have the method's parameter types: Velocity + // finds no method for a call whose arguments don't fit String regex = args[0].toString(); Object second = args.length > 1 ? args[1] : null; CharSequence text = new DeadlineText(s); switch (methodName) { case "matches": - return args.length == 1 ? Pattern.compile(regex).matcher(text).matches() + return args.length == 1 ? compile(regex).matcher(text).matches() : NOT_HANDLED; case "replaceAll": case "replaceFirst": - return second == null ? NOT_HANDLED : replace(Pattern.compile(regex).matcher(text), - second.toString(), "replaceAll".equals(methodName)); + return args.length == 2 ? replace(s, compile(regex).matcher(text), + second == null ? null : second.toString(), + "replaceAll".equals(methodName)) : NOT_HANDLED; case "split": Integer limit = args.length == 1 ? Integer.valueOf(0) : toInt(second); if (limit == null) { return NOT_HANDLED; } - return split(s, Pattern.compile(regex).matcher(text), limit); + return split(s, compile(regex).matcher(text), limit); default: return NOT_HANDLED; } @@ -116,39 +124,33 @@ private static String[] split(String s, Matcher m, int limit) { } private static Integer toInt(Object value) { - if (value instanceof Number) { - return ((Number) value).intValue(); - } - if (value instanceof String) { - try { - return Integer.valueOf(((String) value).trim()); - } catch (NumberFormatException ex) { - return null; - } - } - return null; + return value instanceof Number ? Integer.valueOf(((Number) value).intValue()) : null; } /** * Matcher.replaceAll and replaceFirst, checking before each replacement, * and before the text after the last one, that it can't take the result - * past the output limit: a replacement adds at most its own length plus, - * for each group reference ($1, ${name}) in it, the longest group of that - * match. + * past the output limit: a replacement adds its own length plus the + * length of each group it refers to ($1, ${name}) in that match. */ - private static String replace(Matcher m, String replacement, boolean all) { - long references = replacement.chars().filter(c -> c == '$').count(); + private static String replace(String s, Matcher m, String replacement, boolean all) { + if (replacement == null) { + // as Matcher does: replaceFirst refuses null at once, and + // replaceAll only once there is something to replace + if (!all || m.find()) { + throw new NullPointerException("replacement"); + } + return s; + } + List references = groupReferences(replacement, m.groupCount()); StringBuilder out = new StringBuilder(); int previousEnd = 0; while (m.find()) { - long longestGroup = 0; - for (int g = 0; g <= m.groupCount(); g++) { - if (m.start(g) >= 0) { - longestGroup = Math.max(longestGroup, m.end(g) - m.start(g)); - } + long grown = replacement.length(); + for (Object reference : references) { + grown += groupLength(m, reference); } - RenderSession.checkLength((long) out.length() + (m.start() - previousEnd) - + replacement.length() + references * longestGroup); + RenderSession.checkLength((long) out.length() + (m.start() - previousEnd) + grown); m.appendReplacement(out, replacement); previousEnd = m.end(); if (!all) { @@ -161,6 +163,254 @@ private static String replace(Matcher m, String replacement, boolean all) { return out.toString(); } + /** + * @return the groups a replacement refers to, as group numbers and names, + * read the way Matcher.appendReplacement reads them. A reference + * it would refuse ends the list; appendReplacement then throws. + */ + private static List groupReferences(String replacement, int groupCount) { + List references = new ArrayList<>(); + int i = 0; + int n = replacement.length(); + while (i < n) { + char c = replacement.charAt(i++); + if (c == '\\') { + i++; + } else if (c == '$') { + if (i >= n) { + break; + } + if (replacement.charAt(i) == '{') { + int close = replacement.indexOf('}', i); + if (close < 0) { + break; + } + references.add(replacement.substring(i + 1, close)); + i = close + 1; + } else { + int group = replacement.charAt(i) - '0'; + if (group < 0 || group > 9) { + break; + } + // more digits are read while they name a group that exists + for (i++; i < n; i++) { + int digit = replacement.charAt(i) - '0'; + if (digit < 0 || digit > 9 || group * 10 + digit > groupCount) { + break; + } + group = group * 10 + digit; + } + references.add(group); + } + } + } + return references; + } + + private static long groupLength(Matcher m, Object reference) { + try { + int start = reference instanceof Integer ? m.start((Integer) reference) + : m.start((String) reference); + int end = reference instanceof Integer ? m.end((Integer) reference) + : m.end((String) reference); + return start < 0 ? 0 : end - start; + } catch (IndexOutOfBoundsException | IllegalArgumentException ex) { + // appendReplacement throws for a group that doesn't exist + return 0; + } + } + + private static Pattern compile(String regex) { + checkPattern(regex); + return Pattern.compile(regex); + } + + /** + * Throws if part of the expression can match an empty string in more + * than one way at the same place: a group or assertion that can match + * empty followed by a quantifier, or a group with two alternatives that + * can. Matching such an expression can try exponentially many ways + * without reading a character, so DeadlineText never gets to check the + * deadline. Whether a part can match empty is tried with Pattern itself, + * on a few short texts; a part that doesn't compile on its own counts as + * one that can. + */ + static void checkPattern(String regex) { + // for each open group: where its body and its current alternative + // start, how many of its alternatives can match empty, and whether + // it is a lookaround, which matches empty whatever it contains + Deque groups = new ArrayDeque<>(); + int n = regex.length(); + int i = 0; + while (i < n) { + char c = regex.charAt(i); + if (c == '\\') { + i = skipEscape(regex, i); + } else if (c == '[') { + i = skipClass(regex, i); + } else if (c == '^' || c == '$') { + i++; + refuseQuantifier(regex, i); + } else if (c == '(') { + int[] group = openGroup(regex, i); + if (group == null) { + // flags such as (?i), which apply to the rest of the group + i = regex.indexOf(')', i) + 1; + if (i == 0) { + return; + } + } else { + groups.push(group); + i = group[0]; + } + } else if (c == '|' && !groups.isEmpty()) { + int[] group = groups.peek(); + if (canMatchEmpty(regex.substring(group[1], i))) { + group[2]++; + } + group[1] = ++i; + } else if (c == ')' && !groups.isEmpty()) { + int[] group = groups.pop(); + boolean alternatives = group[1] != group[0]; + if (alternatives && canMatchEmpty(regex.substring(group[1], i))) { + group[2]++; + } + if (group[2] > 1) { + throw refused(); + } + boolean empty = group[3] == 1 || canMatchEmpty(regex.substring(group[0], i)); + i++; + if (empty) { + refuseQuantifier(regex, i); + } + } else { + i++; + } + } + } + + /** Short texts to try whether part of an expression can match empty in them. */ + private static final String[] EMPTY_MATCH_TEXTS = {"", "a", "a b", "\n", "0_"}; + + private static boolean canMatchEmpty(String part) { + Pattern p; + try { + p = Pattern.compile(part); + } catch (RuntimeException ex) { + return true; + } + for (String text : EMPTY_MATCH_TEXTS) { + Matcher m = p.matcher(text).useTransparentBounds(true).useAnchoringBounds(false); + for (int at = 0; at <= text.length(); at++) { + if (m.region(at, at).matches()) { + return true; + } + } + } + return false; + } + + /** + * @return for the group opening at start: where its body starts, where + * its first alternative starts, 0 alternatives that can match + * empty, and 1 for a lookaround; or null for flags with no body + */ + private static int[] openGroup(String regex, int start) { + int i = start + 1; + if (i >= regex.length() || regex.charAt(i) != '?') { + return new int[] {i, i, 0, 0}; + } + i++; + char c = i < regex.length() ? regex.charAt(i) : 0; + char next = i + 1 < regex.length() ? regex.charAt(i + 1) : 0; + if (c == '=' || c == '!') { + return new int[] {i + 1, i + 1, 0, 1}; + } + if (c == '<' && (next == '=' || next == '!')) { + return new int[] {i + 2, i + 2, 0, 1}; + } + if (c == '<') { + int body = regex.indexOf('>', i) + 1; + body = body == 0 ? regex.length() : body; + return new int[] {body, body, 0, 0}; + } + if (c == ':' || c == '>') { + return new int[] {i + 1, i + 1, 0, 0}; + } + while (i < regex.length() && (Character.isLetter(regex.charAt(i)) + || regex.charAt(i) == '-')) { + i++; + } + if (i < regex.length() && regex.charAt(i) == ':') { + return new int[] {i + 1, i + 1, 0, 0}; + } + return null; + } + + /** @return the index after the escape at i; a quantified backreference or boundary is refused */ + private static int skipEscape(String regex, int i) { + char c = i + 1 < regex.length() ? regex.charAt(i + 1) : 0; + if (c == 'Q') { + int end = regex.indexOf("\\E", i + 2); + return end < 0 ? regex.length() : end + 2; + } + int end = Math.min(i + 2, regex.length()); + if (c == 'k') { + int close = regex.indexOf('>', i); + end = close < 0 ? regex.length() : close + 1; + } else if (c >= '1' && c <= '9') { + while (end < regex.length() && Character.isDigit(regex.charAt(end))) { + end++; + } + } else if ("bBAGzZ".indexOf(c) < 0 || c == 0) { + return end; + } + // a backreference can match empty, and boundaries always do + refuseQuantifier(regex, end); + return end; + } + + /** @return the index after the character class that opens at i */ + private static int skipClass(String regex, int i) { + int depth = 0; + int n = regex.length(); + while (i < n) { + char c = regex.charAt(i); + if (c == '\\') { + i += 2; + continue; + } + if (c == '[') { + depth++; + i++; + // a ']' first in a class, after any '^', is a plain character + if (i < n && regex.charAt(i) == '^') { + i++; + } + if (i < n && regex.charAt(i) == ']') { + i++; + } + continue; + } + i++; + if (c == ']' && --depth == 0) { + return i; + } + } + return n; + } + + private static void refuseQuantifier(String regex, int i) { + if (i < regex.length() && "?*+{".indexOf(regex.charAt(i)) >= 0) { + throw refused(); + } + } + + private static RenderLimitException refused() { + return new RenderLimitException("a regular expression repeats a part that" + + " can match an empty string"); + } + /** A string that checks the deadline every few thousand character reads. */ private static final class DeadlineText implements CharSequence { diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java index bc43bf047c..af8228b611 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java @@ -43,9 +43,14 @@ */ final class StringGrowth { - /** String methods that are not offered to templates. */ + /** + * String methods that are not offered to templates: those that build a + * string whose length can't be worked out from the call, and those that + * run a regular expression or return a piece for every line, which + * DeadlineRegex doesn't run for them. + */ private static final Set REFUSED_STRING_METHODS = Set.of( - "repeat", "format", "formatted", "join", "indent"); + "repeat", "format", "formatted", "join", "indent", "splitWithDelimiters", "lines"); /** String methods whose result is never longer than the receiver or an argument. */ private static final Set NON_GROWING_STRING_METHODS = Set.of( @@ -180,8 +185,8 @@ static long maxResultLength(Object receiver, String methodName, Object[] args) { } private static long forUtilities(String methodName, Object[] a) { - // Velocity converts arguments to the method's parameter types after - // this sees them, so a number passed for a string is counted as one + // the arguments already have the method's parameter types: Velocity + // finds no method for a call whose arguments don't fit CharSequence s = a.length > 0 ? text(a[0]) : null; switch (methodName) { case "replace": { diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegexTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegexTest.java index 4278400870..63f0a24db2 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegexTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegexTest.java @@ -36,13 +36,69 @@ class DeadlineRegexTest { private static final String[] PATTERNS = {"", ",", "\\s+", "l+", "(?=(.*))", "(.)", "\\b", "$"}; private static final String[] REPLACEMENTS = {"", "x", "$0", "[$1]", "\\$"}; + /** + * Expressions in which part can match an empty string in more than one + * way at the same place are refused; the rest, including ones with + * optional parts, lookarounds and alternatives, still run. + */ + @Test + void refusesExpressionsThatRepeatAnEmptyMatch() { + String[] refused = { + "(?:a?|b?)c", "(|)z", "(?:)*", "x(?:(?:)?){3}", "\\b*", "(?=)+", "^?a", + "()\\1*", "(?:(?:a|){2})", "(?a*|b*)", "(?i:x?|y?)", "((a)|(b)?|c*)d", + }; + for (String regex : refused) { + assertThrows(RenderLimitException.class, () -> DeadlineRegex.checkPattern(regex), + regex); + } + String[] allowed = { + "", "a", "(\\d+)-(\\d+)", "(?i)foo|bar", "(ab)+", "^\\s+|\\s+$", + "(https?://)?(www\\.)?", "foo(?=\\s|$)", "[()|?*]+", "\\Q(|)*\\E", + "(?\\d{4})-(\\d{2})", "a|", "(a|b|)c", "(?:\\.\\d+)?", "(\\w)\\1", + "(.*a){12}b", "[^\\]()]*", + }; + for (String regex : allowed) { + DeadlineRegex.checkPattern(regex); + } + for (String p : PATTERNS) { + DeadlineRegex.checkPattern(p); + } + } + + /** As String does: replaceFirst refuses null, and replaceAll does once it matches. */ + @Test + void aNullReplacementIsRefusedAsByString() { + assertThrows(NullPointerException.class, + () -> DeadlineRegex.invoke("abc", "replaceAll", new Object[] {"b", null})); + assertThrows(NullPointerException.class, + () -> DeadlineRegex.invoke("abc", "replaceFirst", new Object[] {"x", null})); + assertEquals("abc", DeadlineRegex.invoke("abc", "replaceAll", new Object[] {"x", null})); + } + + /** + * A replacement is counted by the groups it refers to, so moving text + * around in a string near the limit still works. + */ @Test - void convertsArgumentsAsVelocityWould() { - assertArrayEquals("a,b,c".split(",", 2), - (String[]) DeadlineRegex.invoke("a,b,c", "split", new Object[] {",", "2"})); - assertArrayEquals("a,b,c".split(",", 2), - (String[]) DeadlineRegex.invoke("a,b,c", "split", new Object[] {",", 2L})); - assertEquals("a1b1c", DeadlineRegex.invoke("a,b,c", "replaceAll", new Object[] {",", 1})); + void replacementsCountOnlyTheGroupsTheyUse() { + RenderSession session = RenderSession.begin(null); + try { + int length = (int) (session.getMaxOutputChars() * 3 / 5); + String s = "abc" + "0".repeat(length - 3); + String swapped = (String) DeadlineRegex.invoke(s, "replaceAll", + new Object[] {"(?s)^(.)(.)(.)(.*)$", "$3$2$1$4"}); + assertEquals(length, swapped.length()); + assertEquals("cba0", swapped.substring(0, 4)); + assertEquals("", DeadlineRegex.invoke("b", "replaceAll", + new Object[] {"(?b)", "<${x}>"})); + assertEquals("b1", DeadlineRegex.invoke("b", "replaceAll", + new Object[] {"(b)", "$11"})); + // a group used twice is counted twice + assertThrows(RenderLimitException.class, () -> DeadlineRegex.invoke(s, "replaceAll", + new Object[] {"(?s)^(.*)$", "$1$1"})); + } finally { + session.end(); + } } @Test diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java index e224f0c360..417ecd8bb7 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java @@ -249,7 +249,7 @@ void utilitiesCallsOnPlainTextAreNotOverestimated() { assertEquals(text.length(), StringGrowth.maxResultLength(utils, name, new Object[] {text}), name); } - // Velocity converts a number to the string the method takes + // a value that isn't a string is counted by its text assertTrue(StringGrowth.maxResultLength(utils, "escapeHTML", new Object[] {12345}) <= 5); assertTrue(StringGrowth.maxResultLength(utils, "escapeHTML", new Object[] {new StringBuilder("<<= "<<<ab".length()); From 5e79d9bb66b0fbc894183a263a377e544678dd41 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Fri, 20 Nov 2026 14:24:20 -0700 Subject: [PATCH 14/18] Fail the render when a #foreach runs past 100,000 passes Velocity's directive.foreach.max_loops ends a loop without an error, so a page cut short by it was served and cached as if it were whole. RollerForeach now fails the render on the pass after the 100,000th, like the other limits, and the property is gone from velocity.properties. A loop of exactly 100,000 passes still completes. The tests' check that Roller's limit, not the test's own ceiling, stopped a render followed getCause, which RenderingException doesn't set, so it never saw the ceiling. It now follows the root cause. --- .../ui/rendering/velocity/RollerForeach.java | 40 ++++++++++++++- .../main/webapp/WEB-INF/velocity.properties | 1 - .../rendering/velocity/RenderLimitsTest.java | 51 +++++++++++++++++-- .../velocity/RollerVelocityTestSupport.java | 23 +++++++++ .../resources/WEB-INF/velocity.properties | 1 - 5 files changed, 109 insertions(+), 7 deletions(-) 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 index 931f71193c..b5cce131f6 100644 --- 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 @@ -21,6 +21,7 @@ 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; @@ -28,15 +29,52 @@ /** * Velocity's #foreach, checking the render deadline on every pass so a loop - * that writes nothing still stops. Registered in velocity.properties under + * that writes nothing still stops, and failing the render on a loop of more + * than MAX_PASSES passes. Velocity's own directive.foreach.max_loops ends the + * loop without an error, so a page cut short that way would be served and + * cached as if it were whole. Registered in velocity.properties under * runtime.custom_directives, where it replaces the built-in directive. */ public class RollerForeach extends Foreach { + /** Most passes one #foreach may make. */ + static final int MAX_PASSES = 100_000; + + @Override + protected Iterator getIterator(Object iterable, Node node) { + Iterator items = super.getIterator(iterable, node); + return items == null || RenderSession.current() == null ? items : new Limited(items); + } + @Override protected void renderBlock(InternalContextAdapter context, Writer writer, Node block) throws IOException { RenderSession.checkDeadline(); super.renderBlock(context, writer, block); } + + /** The items of one loop, failing the render on the one after the last pass allowed. */ + private static final class Limited implements Iterator { + + private final Iterator items; + private int passes = 0; + + Limited(Iterator items) { + this.items = items; + } + + @Override + public boolean hasNext() { + return items.hasNext(); + } + + @Override + public Object next() { + if (++passes > MAX_PASSES) { + throw new RenderLimitException("#foreach made more than " + + MAX_PASSES + " passes"); + } + return items.next(); + } + } } diff --git a/app/src/main/webapp/WEB-INF/velocity.properties b/app/src/main/webapp/WEB-INF/velocity.properties index 56558672e3..57b65f7208 100644 --- a/app/src/main/webapp/WEB-INF/velocity.properties +++ b/app/src/main/webapp/WEB-INF/velocity.properties @@ -96,7 +96,6 @@ default.contentType=text/html; charset=utf-8 parser.class=org.apache.roller.weblogger.ui.rendering.velocity.RenderLimitParser introspector.uberspect.class=org.apache.velocity.util.introspection.SecureUberspector,org.apache.roller.weblogger.ui.rendering.velocity.RenderLimitUberspector runtime.custom_directives=org.apache.roller.weblogger.ui.rendering.velocity.RollerForeach -directive.foreach.max_loops=100000 event_handler.reference_insertion.class=org.apache.roller.weblogger.ui.rendering.velocity.RenderLimitInsertionHandler # SecureUberspector governs method access, not resource resolution, so the 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 index 50d5b27edb..24789ebbd3 100644 --- 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 @@ -24,6 +24,7 @@ import java.util.HashMap; import java.util.Map; +import org.apache.roller.RollerException; import org.apache.roller.weblogger.ui.rendering.RenderingException; import org.apache.roller.weblogger.ui.rendering.model.UtilitiesModel; import org.apache.roller.weblogger.ui.rendering.mobile.MobileDeviceRepository.DeviceType; @@ -78,8 +79,13 @@ private static Outcome render(String name, String source, Map co 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 = t.getCause()) { + for (; t != null; t = causeOf(t)) { if (t instanceof IllegalStateException && "test ceiling reached".equals(t.getMessage())) { return true; @@ -88,6 +94,28 @@ private static boolean reachedTestCeiling(Throwable t) { return false; } + /** Asserts the render failed with this limit, rather than after doing the work. */ + private static void assertLimit(Outcome outcome, String message) { + assertNotNull(outcome.failure, "rendering should have failed with \"" + message + + "\", but wrote " + outcome.out.getHead()); + Throwable t = outcome.failure; + while (t != null && !(t instanceof RenderLimitException)) { + t = causeOf(t); + } + assertNotNull(t, "rendering failed with something other than a limit: " + + outcome.failure); + assertTrue(t.getMessage().startsWith(message), "stopped by: " + t.getMessage()); + } + + /** Renders with a smaller output limit, so a test needn't build tens of megabytes. */ + private static Outcome renderWithLimit(String name, String source, int maxOutputChars) + throws Exception { + try (AutoCloseable limit = RollerVelocityTestSupport.property( + RenderSession.MAX_OUTPUT_CHARS, String.valueOf(maxOutputChars))) { + return render(name, source); + } + } + private static void assertStoppedByRoller(Outcome outcome) { assertFalse(outcome.out.getCount() > OUTPUT_LIMIT, "rendering wrote " + outcome.out.getCount() + " chars before stopping"); @@ -96,18 +124,33 @@ private static void assertStoppedByRoller(Outcome outcome) { "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 aHugeForeachRangeStopsAtTheLoopLimit() { + public void aHugeForeachRangeFailsAtTheLoopLimit() { assertTimeoutPreemptively(WITHIN, () -> { Outcome outcome = render("limits-foreach.vm", "#foreach($i in [1..2000000000])0123456789#end"); - assertFalse(reachedTestCeiling(outcome.failure), - "only the test's own ceiling stopped rendering"); + 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( 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 index 9fa5e2dff9..ca2e9606b9 100644 --- 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 @@ -30,10 +30,12 @@ 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; @@ -78,6 +80,27 @@ static synchronized void install() throws Exception { 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); diff --git a/app/src/test/resources/WEB-INF/velocity.properties b/app/src/test/resources/WEB-INF/velocity.properties index a2241fac0c..ace39ae95a 100644 --- a/app/src/test/resources/WEB-INF/velocity.properties +++ b/app/src/test/resources/WEB-INF/velocity.properties @@ -98,7 +98,6 @@ default.contentType=text/html; charset=utf-8 parser.class=org.apache.roller.weblogger.ui.rendering.velocity.RenderLimitParser introspector.uberspect.class=org.apache.velocity.util.introspection.SecureUberspector,org.apache.roller.weblogger.ui.rendering.velocity.RenderLimitUberspector runtime.custom_directives=org.apache.roller.weblogger.ui.rendering.velocity.RollerForeach -directive.foreach.max_loops=100000 event_handler.reference_insertion.class=org.apache.roller.weblogger.ui.rendering.velocity.RenderLimitInsertionHandler # SecureUberspector governs method access, not resource resolution, so the From a6fc1bc648269351c0eb11ea5a510ea8fa67c3d3 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Fri, 20 Nov 2026 14:24:21 -0700 Subject: [PATCH 15/18] Count the strings and list items a render builds, and check lists, maps and numbers before a call runs The output limit stops what a template writes, but not what it keeps in memory, or what one call builds before its result is checked. - A render may build at most ten times rendering.maxOutputChars characters of strings, counted where they are built (string literals, + and string calls), and add at most 1,000,000 items to lists and maps or get them from split calls. A session started inside another one shares its budget. - A list or map is measured as text, without building the text, before it is inserted, passed to toString, String.valueOf or +, or compared with a string by == or !=. - addAll and putAll are checked against the item budget before they copy anything. containsAll, removeAll and retainAll are refused when they would compare more than 10,000,000 pairs of elements. - Numbers stop at 100,000 bits: pow, the shifts, the bit setters and * are checked before they run, and primality tests aren't offered. - $utils.split is refused when it would return more pieces than a #foreach can visit, as String.split already was. - A Class object offers only getName, so String.format and join can't be reached as static methods. - An error from a regular expression call, such as a replacement naming a group that doesn't exist, shows the template error page again instead of failing the page. - A blank or non-numeric rendering.maxOutputChars or rendering.maxRenderSeconds falls back to the default with a warning instead of failing every page, and the limit messages say which limit was reached. --- .../velocity/RenderLimitInsertionHandler.java | 7 + .../rendering/velocity/RenderLimitParser.java | 106 +++++++- .../velocity/RenderLimitUberspector.java | 59 +++- .../ui/rendering/velocity/RenderSession.java | 125 +++++++-- .../ui/rendering/velocity/StringGrowth.java | 47 +++- .../ui/rendering/velocity/ValueLimits.java | 253 ++++++++++++++++++ .../roller/weblogger/config/roller.properties | 5 +- .../main/webapp/WEB-INF/velocity.properties | 20 +- .../rendering/velocity/RenderLimitsTest.java | 209 +++++++++++++++ .../resources/WEB-INF/velocity.properties | 20 +- 10 files changed, 801 insertions(+), 50 deletions(-) create mode 100644 app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/ValueLimits.java 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 index 55f2b93166..fc5bdae957 100644 --- 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 @@ -19,6 +19,9 @@ package org.apache.roller.weblogger.ui.rendering.velocity; +import java.util.Collection; +import java.util.Map; + import org.apache.velocity.app.event.ReferenceInsertionEventHandler; import org.apache.velocity.context.Context; @@ -32,8 +35,12 @@ public class RenderLimitInsertionHandler implements ReferenceInsertionEventHandl @Override public Object referenceInsert(Context context, String reference, Object value) { RenderSession.checkDeadline(); + RenderSession session = RenderSession.current(); if (value instanceof CharSequence) { RenderSession.checkLength(((CharSequence) value).length()); + } else if (session != null && (value instanceof Collection || value instanceof Map)) { + // a list or map is written as text, built in full before it is written + RenderSession.checkLength(ValueLimits.textLength(value, session.getMaxOutputChars())); } return value; } diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitParser.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitParser.java index 7b117b806e..331215b1d6 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitParser.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitParser.java @@ -23,6 +23,8 @@ import java.io.Reader; import java.io.Writer; import java.lang.reflect.Field; +import java.util.Collection; +import java.util.Map; import org.apache.velocity.Template; import org.apache.velocity.context.InternalContextAdapter; @@ -32,6 +34,9 @@ import org.apache.velocity.runtime.parser.StandardParser; import org.apache.velocity.runtime.parser.node.ASTAddNode; import org.apache.velocity.runtime.parser.node.ASTBlock; +import org.apache.velocity.runtime.parser.node.ASTEQNode; +import org.apache.velocity.runtime.parser.node.ASTMulNode; +import org.apache.velocity.runtime.parser.node.ASTNENode; import org.apache.velocity.runtime.parser.node.ASTprocess; import org.apache.velocity.runtime.parser.node.Node; import org.apache.velocity.runtime.parser.node.SimpleNode; @@ -47,9 +52,14 @@ *
  • a template's root node and every block (the body of #if, #foreach, * #define, #macro and so on) count what they write into any writer that isn't * already counted, such as the buffer of a string literal;
  • - *
  • + checks the length of two strings before joining them.
  • + *
  • + checks the length of two strings before joining them;
  • + *
  • == and != check the length of a list or map before comparing it with + * a string as text;
  • + *
  • * checks the size of two big numbers before multiplying them.
  • * * + *

    The strings they build count toward the render's budget (RenderSession). + * *

    The nodes keep no state of their own between renders, so a parsed * template is still safe to share between threads. */ @@ -79,6 +89,12 @@ private void limitChildren(Node node) { limited = new LimitedBlock(this, (ASTBlock) child); } else if (child.getClass() == ASTAddNode.class) { limited = new LimitedAddNode(this, (ASTAddNode) child); + } else if (child.getClass() == ASTEQNode.class) { + limited = new LimitedEQNode(this, (ASTEQNode) child); + } else if (child.getClass() == ASTNENode.class) { + limited = new LimitedNENode(this, (ASTNENode) child); + } else if (child.getClass() == ASTMulNode.class) { + limited = new LimitedMulNode(this, (ASTMulNode) child); } if (limited != child) { node.jjtAddChild(limited, i); @@ -135,6 +151,7 @@ static final class CountingWriter extends Writer { private void count(long len) { written += len; RenderSession.checkLength(written); + RenderSession.chargeBuilt(len); RenderSession.checkDeadline(); } @@ -229,15 +246,96 @@ static final class LimitedAddNode extends ASTAddNode { @Override protected Object handleSpecial(Object left, Object right, InternalContextAdapter context) { - if (left instanceof CharSequence && right instanceof CharSequence) { - RenderSession.checkLength((long) ((CharSequence) left).length() - + ((CharSequence) right).length()); + if (left instanceof CharSequence || right instanceof CharSequence) { + RenderSession.checkLength(textLength(left) + textLength(right)); } Object result = super.handleSpecial(left, right, context); if (result instanceof CharSequence) { RenderSession.checkLength(((CharSequence) result).length()); + RenderSession.chargeBuilt(((CharSequence) result).length()); } return result; } + + @Override + public Number perform(Number left, Number right, InternalContextAdapter context) { + Number result = super.perform(left, right, context); + ValueLimits.checkResult(result); + return result; + } + } + + /** + * @return the length of a string, or of the text of a list or map, that + * Velocity is about to build; 0 for other values, whose text is + * short or checked once it is built + */ + private static long textLength(Object value) { + RenderSession session = RenderSession.current(); + if (session == null) { + return 0; + } + if (value instanceof CharSequence || value instanceof Collection + || value instanceof Map) { + return ValueLimits.textLength(value, session.getMaxOutputChars()); + } + return 0; + } + + /** Checks the text of a list or map before == compares it with a string. */ + private static void checkComparedText(Object left, Object right) { + if (!left.getClass().isAssignableFrom(right.getClass()) + && !right.getClass().isAssignableFrom(left.getClass())) { + RenderSession.checkLength(textLength(left)); + RenderSession.checkLength(textLength(right)); + } + } + + static final class LimitedEQNode extends ASTEQNode { + + LimitedEQNode(Parser parser, ASTEQNode from) { + super(parser, from.getType()); + moveChildren(from, this); + this.last = from.getLastToken(); + this.template = from.getTemplate(); + } + + @Override + public boolean compareNonNumber(Object left, Object right) { + checkComparedText(left, right); + return super.compareNonNumber(left, right); + } + } + + static final class LimitedNENode extends ASTNENode { + + LimitedNENode(Parser parser, ASTNENode from) { + super(parser, from.getType()); + moveChildren(from, this); + this.last = from.getLastToken(); + this.template = from.getTemplate(); + } + + @Override + public boolean compareNonNumber(Object left, Object right) { + checkComparedText(left, right); + return super.compareNonNumber(left, right); + } + } + + static final class LimitedMulNode extends ASTMulNode { + + LimitedMulNode(Parser parser, ASTMulNode from) { + super(parser, from.getType()); + moveChildren(from, this); + this.last = from.getLastToken(); + this.template = from.getTemplate(); + } + + @Override + public Number perform(Number left, Number right, InternalContextAdapter context) { + ValueLimits.checkBits(ValueLimits.bits(left) + ValueLimits.bits(right)); + return super.perform(left, right, context); + } } } diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitUberspector.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitUberspector.java index 2f4a7ecaa2..ec848e285d 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitUberspector.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/RenderLimitUberspector.java @@ -21,10 +21,13 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.util.Collection; import java.util.Iterator; +import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.apache.roller.weblogger.ui.rendering.model.UtilitiesModel; import org.apache.velocity.util.introspection.AbstractChainableUberspector; import org.apache.velocity.util.introspection.Info; import org.apache.velocity.util.introspection.VelMethod; @@ -88,17 +91,55 @@ private static final class LimitedMethod implements VelMethod { public Object invoke(Object o, Object[] params) throws IllegalAccessException, InvocationTargetException { RenderSession.checkDeadline(); - if (RenderSession.current() != null) { - RenderSession.checkLength(StringGrowth.maxResultLength( - o, method.getMethodName(), params)); - if (o instanceof String) { - Object result = DeadlineRegex.invoke((String) o, method.getMethodName(), params); - if (result != DeadlineRegex.NOT_HANDLED) { - return checked(result); - } + RenderSession session = RenderSession.current(); + if (session == null) { + return method.invoke(o, params); + } + String name = method.getMethodName(); + Object[] args = params == null ? new Object[0] : params; + + // before the call: what it can build or take has to fit + RenderSession.checkLength(StringGrowth.maxResultLength(o, name, args)); + StringGrowth.checkPieces(o, name, args); + ValueLimits.checkNumberCall(o, name, args); + boolean container = o instanceof Collection || o instanceof Map; + if (container) { + ValueLimits.checkContainerCall(o, name, args, session.getMaxOutputChars()); + } + long sizeBefore = ValueLimits.size(o); + boolean builder = o instanceof StringBuilder || o instanceof StringBuffer; + long lengthBefore = builder ? ((CharSequence) o).length() : 0; + + Object result = DeadlineRegex.NOT_HANDLED; + if (o instanceof String) { + try { + result = DeadlineRegex.invoke((String) o, name, args); + } catch (RenderLimitException ex) { + throw ex; + } catch (RuntimeException ex) { + // reported as a template error, as the String method's own is + throw new InvocationTargetException(ex); + } + } + if (result == DeadlineRegex.NOT_HANDLED) { + result = method.invoke(o, params); + } + + // after the call: count what it built toward the render's budget + checked(result); + ValueLimits.checkResult(result); + if (container) { + RenderSession.chargeItems(ValueLimits.size(o) - sizeBefore); + } else if (builder) { + RenderSession.chargeBuilt(((CharSequence) o).length() - lengthBefore); + } else if (o instanceof String || o instanceof UtilitiesModel) { + if (result instanceof CharSequence && result != o) { + RenderSession.chargeBuilt(((CharSequence) result).length()); + } else if (result instanceof Object[]) { + RenderSession.chargeItems(((Object[]) result).length); } } - return checked(method.invoke(o, params)); + return result; } @Override 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 index a0dc00dae7..b21658a0d9 100644 --- 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 @@ -21,6 +21,8 @@ import java.util.concurrent.TimeUnit; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.apache.roller.weblogger.config.WebloggerConfig; /** @@ -31,9 +33,17 @@ * (the resource loader, the output writer, #foreach, introspection and * reference insertion) check the current session rather than trusting the * template. Outside a session those hooks apply no limits. + * + *

    Besides the output and time limits, a render has a budget for what it + * builds in memory: the characters of the strings it makes, and the items it + * adds to lists and maps. A template that keeps many strings or a long list + * never writes them, so the output limit alone doesn't stop it. A session + * started inside another one shares that one's time and budget. */ final class RenderSession { + private static final Log LOG = LogFactory.getLog(RenderSession.class); + /** Most characters one render may write, or put in one string. */ static final String MAX_OUTPUT_CHARS = "rendering.maxOutputChars"; @@ -43,25 +53,59 @@ final class RenderSession { private static final int DEFAULT_MAX_OUTPUT_CHARS = 10 * 1024 * 1024; private static final int DEFAULT_MAX_RENDER_SECONDS = 30; + /** The characters of strings one render may build, as a multiple of the output limit. */ + static final int BUILT_CHARS_PER_OUTPUT_CHAR = 10; + + /** Most items one render may add to lists and maps, or get from split calls. */ + static final long MAX_ITEMS = 1_000_000; + private static final ThreadLocal CURRENT = new ThreadLocal<>(); private final String weblogId; - private final long maxOutputChars; - private final int maxRenderSeconds; - private final long deadline; + private final Budget budget; private final RenderSession previous; + /** What one render may use, shared by the sessions started inside it. */ + private static final class Budget { + final long maxOutputChars; + final int maxRenderSeconds; + final long deadline; + final long maxBuiltChars; + final long maxItems; + long builtChars = 0; + long items = 0; + + Budget() { + int chars = intProperty(MAX_OUTPUT_CHARS, DEFAULT_MAX_OUTPUT_CHARS); + maxOutputChars = chars > 0 ? chars : Long.MAX_VALUE; + maxBuiltChars = chars > 0 ? (long) chars * BUILT_CHARS_PER_OUTPUT_CHAR + : Long.MAX_VALUE; + maxItems = chars > 0 ? MAX_ITEMS : Long.MAX_VALUE; + maxRenderSeconds = intProperty(MAX_RENDER_SECONDS, DEFAULT_MAX_RENDER_SECONDS); + deadline = maxRenderSeconds > 0 + ? System.nanoTime() + TimeUnit.SECONDS.toNanos(maxRenderSeconds) + : 0; + } + } + private RenderSession(String weblogId, RenderSession previous) { this.weblogId = weblogId; this.previous = previous; - int chars = WebloggerConfig.getIntProperty(MAX_OUTPUT_CHARS, - DEFAULT_MAX_OUTPUT_CHARS); - this.maxOutputChars = chars > 0 ? chars : Long.MAX_VALUE; - this.maxRenderSeconds = WebloggerConfig.getIntProperty(MAX_RENDER_SECONDS, - DEFAULT_MAX_RENDER_SECONDS); - this.deadline = maxRenderSeconds > 0 - ? System.nanoTime() + TimeUnit.SECONDS.toNanos(maxRenderSeconds) - : 0; + this.budget = previous != null ? previous.budget : new Budget(); + } + + /** @return the property's value, or the default when it isn't a number */ + private static int intProperty(String name, int defaultValue) { + String value = WebloggerConfig.getProperty(name); + if (value == null || value.isBlank()) { + return defaultValue; + } + try { + return Integer.parseInt(value.trim()); + } catch (NumberFormatException ex) { + LOG.warn(name + " is not a number, using " + defaultValue + ": " + value); + return defaultValue; + } } /** @@ -95,25 +139,68 @@ String getWeblogId() { } long getMaxOutputChars() { - return maxOutputChars; + return budget.maxOutputChars; } /** Throws once the current render has used up its time. */ static void checkDeadline() { RenderSession session = CURRENT.get(); - if (session != null && session.maxRenderSeconds > 0 - && System.nanoTime() - session.deadline > 0) { + if (session != null && session.budget.maxRenderSeconds > 0 + && System.nanoTime() - session.budget.deadline > 0) { throw new RenderLimitException("rendering took longer than " - + session.maxRenderSeconds + " seconds"); + + session.budget.maxRenderSeconds + " seconds"); } } - /** Throws if a value is longer than one render may write. */ + /** 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.maxOutputChars) { - throw new RenderLimitException("rendering produced more than " - + session.maxOutputChars + " characters"); + if (session != null && length > session.budget.maxOutputChars) { + throw new RenderLimitException("a string would be longer than " + + session.budget.maxOutputChars + " characters"); } } + + /** Counts the characters of a string the render built. */ + static void chargeBuilt(long chars) { + RenderSession session = CURRENT.get(); + if (session != null && chars > 0) { + Budget b = session.budget; + b.builtChars = add(b.builtChars, chars); + if (b.builtChars > b.maxBuiltChars) { + throw new RenderLimitException("rendering built more than " + + b.maxBuiltChars + " characters of strings"); + } + } + } + + /** Throws, without counting them, if this many more items would be over the budget. */ + static void checkItems(long count) { + RenderSession session = CURRENT.get(); + if (session != null && add(session.budget.items, count) > session.budget.maxItems) { + throw itemsException(session.budget); + } + } + + /** Counts items the render added to a list or map, or got from a split. */ + static void chargeItems(long count) { + RenderSession session = CURRENT.get(); + if (session != null && count > 0) { + Budget b = session.budget; + b.items = add(b.items, count); + if (b.items > b.maxItems) { + throw itemsException(b); + } + } + } + + private static RenderLimitException itemsException(Budget b) { + return new RenderLimitException("rendering added more than " + + b.maxItems + " items to lists and maps"); + } + + private static long add(long a, long b) { + long sum = a + b; + return sum < 0 ? Long.MAX_VALUE : sum; + } } diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java index af8228b611..149f744dc5 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowth.java @@ -56,7 +56,7 @@ final class StringGrowth { private static final Set NON_GROWING_STRING_METHODS = Set.of( "substring", "subSequence", "trim", "strip", "stripLeading", "stripTrailing", "stripIndent", "translateEscapes", "intern", - "toString", "valueOf", "copyValueOf"); + "toString", "copyValueOf"); /** StringBuilder and StringBuffer methods that are not offered to templates. */ private static final Set REFUSED_BUILDER_METHODS = Set.of("repeat"); @@ -107,6 +107,12 @@ private StringGrowth() { * build a string whose length can't be worked out from the call */ static boolean isRefused(Object receiver, String methodName, Class returnType) { + if (receiver instanceof Class) { + // Velocity calls a class's static methods on its Class object, + // which would offer String.format and join by another name. + // SecureUberspector allows only getName of Class's own methods. + return !"getName".equals(methodName); + } if (receiver instanceof String) { if (REFUSED_STRING_METHODS.contains(methodName)) { return true; @@ -136,6 +142,7 @@ private static boolean isBoundedStringMethod(String methodName) { case "concat": case "toUpperCase": case "toLowerCase": + case "valueOf": return true; default: return false; @@ -346,6 +353,9 @@ private static long forString(String s, String methodName, Object[] a) { return 0; case "concat": return add(len, length(a.length > 0 ? a[0] : null)); + case "valueOf": + // a list or map passed as an Object is printed in full + return a.length == 1 ? length(a[0]) : 0; case "toUpperCase": case "toLowerCase": return caseChange(s); @@ -406,9 +416,44 @@ private static long length(Object value) { if (value instanceof char[]) { return ((char[]) value).length; } + if (value instanceof java.util.Collection || value instanceof java.util.Map) { + RenderSession session = RenderSession.current(); + return ValueLimits.textLength(value, + session == null ? Long.MAX_VALUE : session.getMaxOutputChars()); + } return value == null ? 0 : SCALAR_LENGTH; } + /** + * Throws if $utils.split would return more pieces than a template loop + * can visit. It splits at any of the separator characters (whitespace + * when there are none) and drops empty pieces, so the pieces are the + * runs of other characters. + */ + static void checkPieces(Object receiver, String methodName, Object[] args) { + if (!(receiver instanceof UtilitiesModel) || !"split".equals(methodName) + || args == null || args.length != 2 || !(args[0] instanceof CharSequence)) { + return; + } + CharSequence s = (CharSequence) args[0]; + String separators = args[1] == null ? null : args[1].toString(); + long pieces = 0; + boolean inPiece = false; + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + boolean separator = separators == null ? Character.isWhitespace(c) + : separators.indexOf(c) >= 0; + if (!separator && !inPiece) { + pieces++; + } + inPiece = !separator; + } + if (pieces > DeadlineRegex.MAX_SPLIT_PIECES) { + throw new RenderLimitException("split produced more than " + + DeadlineRegex.MAX_SPLIT_PIECES + " pieces"); + } + } + private static long add(long a, long b) { long sum = a + b; return sum < 0 ? Long.MAX_VALUE : sum; diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/ValueLimits.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/ValueLimits.java new file mode 100644 index 0000000000..9cc829607b --- /dev/null +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/ValueLimits.java @@ -0,0 +1,253 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + + +package org.apache.roller.weblogger.ui.rendering.velocity; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.ArrayDeque; +import java.util.Collection; +import java.util.Deque; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +/** + * Bounds for the values other than strings that a template works with: the + * text of a list or map, the lists and maps it grows, and the big numbers + * Velocity makes when arithmetic overflows a long. One call on these can take + * more memory or time than a whole page, and a call can't be stopped once it + * has started, so each is checked before it runs. + */ +final class ValueLimits { + + /** Most bits of a number a template may make. */ + static final long MAX_NUMBER_BITS = 100_000; + + /** Most element comparisons one containsAll, removeAll or retainAll may make. */ + static final long MAX_COMPARISONS = 10_000_000; + + private ValueLimits() { + } + + /** A list or map being walked by textLength. */ + private static final class Frame { + final Object container; + final Iterator items; + boolean first = true; + + Frame(Object container) { + this.container = container; + this.items = container instanceof Map + ? ((Map) container).entrySet().iterator() + : ((Collection) container).iterator(); + } + } + + /** + * @return the length of String.valueOf(value), or a number above limit + * once it is known to be longer. A list or map is walked element + * by element instead of being turned into text, and the walk + * stops at the limit, so a huge or deeply nested one is cheap to + * check. + */ + static long textLength(Object value, long limit) { + if (!isContainer(value)) { + return leafLength(value); + } + Deque walks = new ArrayDeque<>(); + walks.push(new Frame(value)); + // "[]" or "{}" + long length = 2; + while (!walks.isEmpty() && length <= limit) { + Frame walk = walks.peek(); + if (!walk.items.hasNext()) { + walks.pop(); + continue; + } + if (!walk.first) { + // ", " + length += 2; + } + walk.first = false; + Object item = walk.items.next(); + if (walk.container instanceof Map) { + Map.Entry entry = (Map.Entry) item; + // key=value + length += 1 + visit(entry.getKey(), walk, walks) + + visit(entry.getValue(), walk, walks); + } else { + length += visit(item, walk, walks); + } + } + return length; + } + + /** @return the length of item, or 2 for the brackets of a container it starts walking */ + private static long visit(Object item, Frame walk, Deque walks) { + if (item == walk.container) { + // how AbstractCollection and AbstractMap print themselves + return item instanceof Map ? "(this Map)".length() : "(this Collection)".length(); + } + if (isContainer(item)) { + walks.push(new Frame(item)); + return 2; + } + return leafLength(item); + } + + private static boolean isContainer(Object value) { + return value instanceof Collection || value instanceof Map; + } + + private static long leafLength(Object value) { + return value instanceof CharSequence ? ((CharSequence) value).length() + : String.valueOf(value).length(); + } + + /** @return the number of elements of a list or map, or 0 for anything else */ + static long size(Object value) { + if (value instanceof Collection) { + return ((Collection) value).size(); + } + return value instanceof Map ? ((Map) value).size() : 0; + } + + /** + * Checks a call on a list or map before it runs: the items it may add + * from the lists and maps passed to it have to fit the render's budget, + * a comparison of every element with every other has to stay small, and + * the text of toString has to fit the output limit. + */ + static void checkContainerCall(Object receiver, String methodName, Object[] args, + long maxChars) { + long receiverSize = size(receiver); + long added = 0; + for (Object arg : args) { + long argSize = size(arg); + added += argSize; + boolean compares = "containsAll".equals(methodName) && !(receiver instanceof Set) + || ("removeAll".equals(methodName) || "retainAll".equals(methodName)) + && !(arg instanceof Set); + if (compares && receiverSize > 0 && argSize > MAX_COMPARISONS / receiverSize) { + throw new RenderLimitException(methodName + " would compare more than " + + MAX_COMPARISONS + " pairs of elements"); + } + } + RenderSession.checkItems(added); + if ("toString".equals(methodName) && args.length == 0) { + RenderSession.checkLength(textLength(receiver, maxChars)); + } + } + + /** + * Checks a call on a big number before it runs, for the calls whose + * result can be far larger than the number: pow, the shifts and the bit + * setters. Primality tests are refused, as they can take minutes on a + * number that fits the limit. + */ + static void checkNumberCall(Object receiver, String methodName, Object[] args) { + if (receiver instanceof BigInteger) { + BigInteger n = (BigInteger) receiver; + long arg = args.length == 1 && args[0] instanceof Number + ? ((Number) args[0]).longValue() : 0; + long bits; + switch (methodName) { + case "pow": + bits = multiply(n.bitLength(), Math.max(arg, 0)); + break; + case "shiftLeft": + bits = n.bitLength() + Math.max(arg, 0); + break; + case "shiftRight": + bits = n.bitLength() - Math.min(arg, 0); + break; + case "setBit": + case "flipBit": + bits = Math.max(n.bitLength(), arg + 1); + break; + case "isProbablePrime": + case "nextProbablePrime": + throw new RenderLimitException(methodName + " is not available to templates"); + default: + bits = 0; + } + checkBits(bits); + } else if (receiver instanceof BigDecimal) { + BigDecimal d = (BigDecimal) receiver; + long arg = args.length > 0 && args[0] instanceof Number + ? Math.abs(((Number) args[0]).longValue()) : 0; + // a scale far from zero is cheap to hold, but these write it out + // in full, at a little over three bits a digit + long scale = Math.abs((long) d.scale()); + switch (methodName) { + case "pow": + checkBits(multiply(bits(d), arg)); + break; + case "toPlainString": + case "toBigInteger": + case "toBigIntegerExact": + checkBits(bits(d) + 4 * scale); + break; + case "setScale": + case "movePointLeft": + case "movePointRight": + case "scaleByPowerOfTen": + checkBits(bits(d) + 4 * (scale + arg)); + break; + default: + break; + } + } + } + + /** Throws if a number a template made is larger than MAX_NUMBER_BITS. */ + static void checkResult(Object result) { + if (result instanceof BigInteger || result instanceof BigDecimal) { + checkBits(bits((Number) result)); + } + } + + /** @return about how many bits a number holds */ + static long bits(Number n) { + if (n instanceof BigInteger) { + return ((BigInteger) n).bitLength(); + } + if (n instanceof BigDecimal) { + // a little over three bits a digit + return ((BigDecimal) n).precision() * 4L; + } + return Long.SIZE; + } + + static void checkBits(long bits) { + if (bits > MAX_NUMBER_BITS) { + throw new RenderLimitException("a number would have more than " + + MAX_NUMBER_BITS + " bits"); + } + } + + private static long multiply(long a, long b) { + if (a == 0 || b == 0) { + return 0; + } + return a > Long.MAX_VALUE / b ? Long.MAX_VALUE : a * b; + } +} diff --git a/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties b/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties index 2cd671e2ff..141b21448d 100644 --- a/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties +++ b/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties @@ -496,7 +496,10 @@ velocity.properties=/WEB-INF/velocity.properties # Limits on rendering one weblog page or feed. A template that writes more # characters (or builds a longer string) than maxOutputChars, or takes longer -# than maxRenderSeconds, fails with an error in the log. Zero means no limit. +# than maxRenderSeconds, fails with an error in the log, as does a #foreach of +# more than 100,000 passes. While maxOutputChars is set, a render may also +# build at most ten times that many characters of strings in memory, and add +# at most 1,000,000 items to lists and maps. Zero means no limit. rendering.maxOutputChars=10485760 rendering.maxRenderSeconds=30 diff --git a/app/src/main/webapp/WEB-INF/velocity.properties b/app/src/main/webapp/WEB-INF/velocity.properties index 57b65f7208..ef015936e6 100644 --- a/app/src/main/webapp/WEB-INF/velocity.properties +++ b/app/src/main/webapp/WEB-INF/velocity.properties @@ -77,20 +77,24 @@ default.contentType=text/html; charset=utf-8 # Weblog templates are written by weblog authors, so a render is bounded by # rendering.maxOutputChars and rendering.maxRenderSeconds in -# roller.properties. Each setting below does part of that: +# roller.properties, and by a budget for the strings and list items it builds +# in memory (RenderSession). Each setting below does part of that: # - parser.class: RenderLimitParser swaps in nodes that stop string literals, -# + and blocks used as strings at the output limit as they are built. +# + and blocks used as strings at the output limit as they are built, check +# the text of a list or map before == or != compares it with a string, and +# check the size of big numbers before * multiplies them. # - introspector.uberspect.class: RenderLimitUberspector, chained after # SecureUberspector, checks the deadline on every method call and property # read, stops a call that returns or could build a string longer than the -# output limit, and runs regular expressions given to String methods under +# output limit, a list or map past the budget, or a number too large to +# work with, and runs regular expressions given to String methods under # the deadline. It does not offer the methods whose result can't be bounded -# from the call: repeat, format, formatted, join and indent on String, any -# other String method returning a string that StringGrowth doesn't know, -# and repeat on StringBuilder and StringBuffer. +# from the call: repeat, format, formatted, join, indent, lines and +# splitWithDelimiters on String, any other String method returning a string +# that StringGrowth doesn't know, repeat on StringBuilder and StringBuffer, +# and the methods of a Class object other than getName. # - runtime.custom_directives: RollerForeach checks the deadline on every -# #foreach pass. -# - directive.foreach.max_loops: a #foreach stops after this many passes. +# #foreach pass, and fails the render on a loop of more than 100,000 passes. # - event_handler.reference_insertion.class: RenderLimitInsertionHandler # checks the deadline, and each inserted value against the output limit. parser.class=org.apache.roller.weblogger.ui.rendering.velocity.RenderLimitParser 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 index 24789ebbd3..24d8f7102f 100644 --- 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 @@ -35,6 +35,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -479,4 +480,212 @@ public void endlessMacroRecursionStopsAtTheDepthLimit() throws Exception { assertTrue(outcome.out.getHead().contains(""), "rendering wrote " + outcome.out.getHead()); } + + /** 81,920 characters, for tests with a limit of 100,000. */ + private static final String EIGHTY_THOUSAND_DIGITS = "#set($s = '0123456789')" + + "#foreach($i in [1..13])#set($s = \"$s$s\")#end"; + + /** A list or map is checked as text before Velocity turns it into one string. */ + @Test + public void aLargeListIsRefusedBeforeItIsWrittenAsText() throws Exception { + String[] uses = { + "$r", + "$r.toString()", + "#set($t = '' + $r)", + "#set($s = 'x')$s.valueOf($r)", + "#if($r == 'x')yes#end", + "#set($m = {'k': $r})$m", + }; + for (int i = 0; i < uses.length; i++) { + Outcome outcome = renderWithLimit("limits-list-text-" + i + ".vm", + "#set($r = [1..2000000])" + uses[i], 100_000); + assertLimit(outcome, "a string would be longer than 100000 characters"); + } + } + + @Test + public void aDeeplyNestedListIsRefusedBeforeItIsWrittenAsText() throws Exception { + Outcome outcome = renderWithLimit("limits-nested-list.vm", + "#set($l = [1])#foreach($i in [1..20])#set($l = [$l, $l])#end$l", 100_000); + assertLimit(outcome, "a string would be longer than 100000 characters"); + } + + @Test + public void smallListsAndMapsStillPrint() throws Exception { + Outcome outcome = render("limits-list-ordinary.vm", + "#set($l = [1, 'two', [3]])#set($m = {'a': 1})" + + "#set($x = $l.add($l))$l $m ${l.size()} #if($m != 'x')ne#end"); + assertEquals(null, outcome.failure); + assertEquals("[1, two, [3], (this Collection)] {a=1} 4 ne", outcome.out.getHead()); + } + + @Test + public void aTemplateThatBuildsAHugeListStopsAtTheLimit() throws Exception { + Outcome doubled = render("limits-list-doubling.vm", + "#set($l = [1])#foreach($i in [1..24])#set($x = $l.addAll($l))#end$l.size()"); + assertLimit(doubled, "rendering added more than 1000000 items"); + + // the range is refused before any of it is copied + Outcome copied = render("limits-list-copy.vm", + "#set($l = [])#set($x = $l.addAll([1..30000000]))$l.size()"); + assertLimit(copied, "rendering added more than 1000000 items"); + + Outcome map = render("limits-map.vm", + "#set($m = {})#foreach($i in [1..1000])#foreach($j in [1..1001])" + + "#set($x = $m.put(\"$i-$j\", $j))#end#end$m.size()"); + assertLimit(map, "rendering added more than 1000000 items"); + } + + @Test + public void aTemplateThatKeepsManyLongStringsStopsAtTheLimit() throws Exception { + // each string is new, so the list would hold 50 times 81,920 characters + Outcome outcome = renderWithLimit("limits-kept-strings.vm", EIGHTY_THOUSAND_DIGITS + + "#set($l = [])#foreach($i in [1..50])#set($x = $l.add(\"$s$i\"))#end" + + "$l.size()", 100_000); + assertLimit(outcome, "rendering built more than 1000000 characters of strings"); + } + + @Test + public void comparingTwoLargeListsElementByElementIsRefused() throws Exception { + Outcome outcome = render("limits-contains-all.vm", + "#set($a = [1..100000])#set($b = [1..200])$a.containsAll($b)"); + assertLimit(outcome, "containsAll would compare more than 10000000 pairs"); + + Outcome ordinary = render("limits-contains-all-ordinary.vm", + "#set($a = [1..1000])#set($b = [1..200])$a.containsAll($b)"); + assertEquals(null, ordinary.failure); + assertEquals("true", ordinary.out.getHead()); + } + + @Test + public void aTemplateThatBuildsAHugeNumberStopsAtTheLimit() throws Exception { + String big = "#set($b = 9223372036854775807 + 1)"; + String[] growth = { + "$b.shiftLeft(200000)", + "$b.pow(5000)", + "$b.setBit(200000)", + "#foreach($i in [1..15])#set($b = $b * $b)#end", + }; + for (int i = 0; i < growth.length; i++) { + Outcome outcome = render("limits-number-" + i + ".vm", big + growth[i]); + assertLimit(outcome, "a number would have more than 100000 bits"); + } + Outcome prime = render("limits-number-prime.vm", big + "$b.isProbablePrime(50)"); + assertLimit(prime, "isProbablePrime is not available to templates"); + + Outcome ordinary = render("limits-number-ordinary.vm", big + "$b.shiftLeft(2) ${b.pow(2)}"); + assertEquals(null, ordinary.failure); + assertEquals("36893488147419103232 85070591730234615865843651857942052864", + ordinary.out.getHead()); + } + + @Test + public void utilitiesSplitIntoMorePiecesThanALoopCanVisitIsRefused() throws Exception { + Map context = new HashMap<>(); + context.put("utils", new UtilitiesModel()); + context.put("s", "a,".repeat(150_000)); + Outcome outcome = render("limits-utils-split.vm", "$utils.split($s, ',').size()", + context); + assertLimit(outcome, "split produced more than 100000 pieces"); + + context.put("s", ",,a,,b,c,,"); + Outcome ordinary = render("limits-utils-split-ordinary.vm", + "$utils.split($s, ',').size()", context); + assertEquals(null, ordinary.failure); + assertEquals("3", ordinary.out.getHead()); + } + + @Test + public void stringMethodsThatSplitWithoutTheLimitsAreNotAvailable() throws Exception { + Outcome outcome = render("limits-split-delimiters.vm", + "#set($s = 'a,b')[$s.splitWithDelimiters(',', 0)][$s.lines()]"); + assertEquals(null, outcome.failure); + assertEquals("[$s.splitWithDelimiters(',', 0)][$s.lines()]", outcome.out.getHead()); + } + + /** Velocity calls a class's static methods on its Class object. */ + @Test + public void staticStringMethodsAreNotAvailableThroughTheClass() throws Exception { + Outcome outcome = render("limits-class-static.vm", + "#set($s = 'x')[$s.class.format('%s', 'y')][$s.getClass().join('-', ['a'])]" + + "[$s.class.name][$s.getClass().getName()]"); + assertEquals(null, outcome.failure); + assertEquals("[$s.class.format('%s', 'y')][$s.getClass().join('-', ['a'])]" + + "[java.lang.String][java.lang.String]", outcome.out.getHead()); + } + + /** + * A replace with a group that doesn't exist, or with no replacement, + * shows the template error page as before, rather than failing the page. + */ + @Test + public void aRegexReplaceTheStringMethodRefusesShowsTheTemplateError() throws Exception { + String[] calls = {"$s.replaceAll('b', '$1')", "$s.replaceAll('b', $nothing)", + "$s.replaceFirst('x', $nothing)"}; + for (int i = 0; i < calls.length; i++) { + Outcome outcome = render("limits-regex-error-" + i + ".vm", + "#set($s = 'abc')[" + calls[i] + "]"); + assertEquals(null, outcome.failure, calls[i]); + assertTrue(outcome.out.getHead().contains(""), + calls[i] + " wrote " + outcome.out.getHead()); + } + Outcome nothingToReplace = render("limits-regex-null-unmatched.vm", + "#set($s = 'abc')[$s.replaceAll('x', $nothing)]"); + assertEquals(null, nothingToReplace.failure); + assertEquals("[abc]", nothingToReplace.out.getHead()); + } + + @Test + public void aRegexThatRepeatsAnEmptyMatchIsRefused() throws Exception { + Outcome outcome = render("limits-regex-empty.vm", + "#set($s = '')$s.matches('(?:a?|b?)(?:a?|b?)c')"); + assertLimit(outcome, "a regular expression repeats a part that can match an empty"); + } + + /** A template error can quote a long value, which the error page shortens. */ + @Test + public void aTemplateErrorAboutALongValueStaysShort() throws Exception { + Outcome outcome = render("limits-long-error.vm", TEN_THOUSAND_DIGITS + + "#set($t = \"x$s\")#set($i = 1)$i.parseInt($t)"); + assertEquals(null, outcome.failure); + assertTrue(outcome.out.getHead().contains(""), + "rendering wrote " + outcome.out.getHead()); + assertTrue(outcome.out.getCount() < 5000, "the error page wrote " + + outcome.out.getCount() + " chars"); + } + + @Test + public void aBlankOrInvalidLimitFallsBackToTheDefault() throws Exception { + for (String value : new String[] {"", " ", "ten"}) { + try (AutoCloseable limit = RollerVelocityTestSupport.property( + RenderSession.MAX_OUTPUT_CHARS, value)) { + RenderSession session = RenderSession.begin(null); + try { + assertEquals(10L * 1024 * 1024, session.getMaxOutputChars(), value); + } finally { + session.end(); + } + } + } + } + + @Test + public void aSessionStartedInsideAnotherSharesItsBudget() throws Exception { + try (AutoCloseable limit = RollerVelocityTestSupport.property( + RenderSession.MAX_OUTPUT_CHARS, "1000")) { + RenderSession outer = RenderSession.begin(null); + try { + RenderSession.chargeBuilt(9000); + RenderSession inner = RenderSession.begin(null); + try { + assertThrows(RenderLimitException.class, + () -> RenderSession.chargeBuilt(2000)); + } finally { + inner.end(); + } + } finally { + outer.end(); + } + } + } } diff --git a/app/src/test/resources/WEB-INF/velocity.properties b/app/src/test/resources/WEB-INF/velocity.properties index ace39ae95a..e44d26142a 100644 --- a/app/src/test/resources/WEB-INF/velocity.properties +++ b/app/src/test/resources/WEB-INF/velocity.properties @@ -79,20 +79,24 @@ default.contentType=text/html; charset=utf-8 # # Weblog templates are written by weblog authors, so a render is bounded by # rendering.maxOutputChars and rendering.maxRenderSeconds in -# roller.properties. Each setting below does part of that: +# roller.properties, and by a budget for the strings and list items it builds +# in memory (RenderSession). Each setting below does part of that: # - parser.class: RenderLimitParser swaps in nodes that stop string literals, -# + and blocks used as strings at the output limit as they are built. +# + and blocks used as strings at the output limit as they are built, check +# the text of a list or map before == or != compares it with a string, and +# check the size of big numbers before * multiplies them. # - introspector.uberspect.class: RenderLimitUberspector, chained after # SecureUberspector, checks the deadline on every method call and property # read, stops a call that returns or could build a string longer than the -# output limit, and runs regular expressions given to String methods under +# output limit, a list or map past the budget, or a number too large to +# work with, and runs regular expressions given to String methods under # the deadline. It does not offer the methods whose result can't be bounded -# from the call: repeat, format, formatted, join and indent on String, any -# other String method returning a string that StringGrowth doesn't know, -# and repeat on StringBuilder and StringBuffer. +# from the call: repeat, format, formatted, join, indent, lines and +# splitWithDelimiters on String, any other String method returning a string +# that StringGrowth doesn't know, repeat on StringBuilder and StringBuffer, +# and the methods of a Class object other than getName. # - runtime.custom_directives: RollerForeach checks the deadline on every -# #foreach pass. -# - directive.foreach.max_loops: a #foreach stops after this many passes. +# #foreach pass, and fails the render on a loop of more than 100,000 passes. # - event_handler.reference_insertion.class: RenderLimitInsertionHandler # checks the deadline, and each inserted value against the output limit. parser.class=org.apache.roller.weblogger.ui.rendering.velocity.RenderLimitParser From 37e1ab1aeb1c4037fcf0150777b1ee8bb32fa7be Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Fri, 20 Nov 2026 14:26:21 -0700 Subject: [PATCH 16/18] Bound $utils.addNofollow for its current implementation addNofollow now adds nofollow to every link, by adding a rel or adding to the link's own one, so the old bound, which only counted links that already had rel="nofollow", was no longer an upper bound. Each "".length(), c -> c == '\n'); case "addNofollow": - // only a link that already has rel="nofollow" gets another + // each link (each "= 0; i = s.indexOf(target, i + target.length())) { - n++; + for (int i = 0; i + target.length() <= s.length(); i++) { + if (s.regionMatches(true, i, target, 0, target.length())) { + n++; + i += target.length() - 1; + } } return n; } diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java index 417ecd8bb7..c2506f686b 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java @@ -181,6 +181,9 @@ void utilitiesStringCallsAreBounded() { texts.add("a<b>b</b><a href='http://x/\u00e9"&'>y</a>" + "<a href=\"mailto:\u03d1é&\"><br />""); texts.add(" "); + // links with no rel, with an unquoted or unclosed rel, and with one to add to + texts.add("".repeat(20) + "z" + + ""); texts.add("mailto:a.b-c@d.example.org, mailto:a.b-c@d.example.org and x@y.z w@v.u."); texts.add("\\u0041 \\x41 \\101 %41 %E2%82%AC 😀 ϑ "); for (Map.Entry> call : oneStringCalls(utils).entrySet()) { From 03782fe1d4c828fe8e6feac49aa733e5001eabcc Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Fri, 20 Nov 2026 14:31:43 -0700 Subject: [PATCH 17/18] Describe the render budget and the per-template macros in CHANGES The #335 entry now says that a long #foreach fails the render rather than stopping, and lists the budget for strings, list items and numbers and the calls templates can't use. Macro scoping gets its own entry, which says what a custom theme that calls a macro from another template sees and how to fix it. --- CHANGES.md | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 549a1ff55c..a55555b95e 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -20,12 +20,24 @@ - **Weblog templates have render limits.** A page stops rendering, with a logged error, once it writes more than `rendering.maxOutputChars` (10 MB) - or runs longer than `rendering.maxRenderSeconds` (30 seconds); `#foreach` - stops at 100,000 passes, and `String.repeat` isn't available. `#parse` and - `#include` load only the weblog's own templates, and macros defined inline - in a template stay with the page that defines them and the templates it - includes. Library macros stay global. Error pages no - longer show template ids (#335). + or runs longer than `rendering.maxRenderSeconds` (30 seconds), and the + page isn't cached. The same happens to a `#foreach` of more than 100,000 + passes, a render that builds more than ten times `maxOutputChars` of + strings in memory or adds more than 1,000,000 items to lists and maps, a + number past 100,000 bits, and a regular expression that repeats a part + that can match an empty string. `String.repeat`, `format`, `join`, `lines` + and `splitWithDelimiters` aren't available, nor are static methods called + through `$x.class`. `#parse` and `#include` load only the weblog's own + templates. Error pages no longer show template ids (#335). +- **Macros defined in a template belong to that template.** A macro defined + inline in a template works in that page and in the templates it + `#parse`s, and one weblog's macro no longer replaces another's of the same + name. A custom theme that calls a macro defined in a different template, + which it doesn't `#parse`, now prints the call as text. Before, such a call + worked only once the defining template had been rendered since the server + started. Define the macro in the page that calls it, or `#parse` the + template that defines it. Library macros (`roller.vm`, `weblog.vm` and a + site's own `roller-custom.vm`) stay global (#335). - **Entries with scripts or embeds open as HTML.** If an entry contains scripts, frames, embedded objects, event-handler attributes or From 71893f03aa5611bc40f68752da0cd672e1cafc7b Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Fri, 20 Nov 2026 14:40:00 -0700 Subject: [PATCH 18/18] Measure map entries and appended lists as text, and count copied list items - A map entry, such as one from entrySet(), is measured as key=value like a map, so a large list inside one is refused before it is printed. - toArray and clone on a list or map count the items they copy against the budget before they run. - StringBuilder.append and insert count a list or map passed as an Object by its text. - Only addAll and putAll count the items of a list passed to them, so adding a large list as one item is one item. - Whether part of a regular expression can match empty no longer depends on sample texts: lookarounds, anchors and boundaries count as matching empty, and the part is also tried in comments mode, which an inline (?x) may have turned on. - The tests use sizes just over the limits. --- .../ui/rendering/velocity/DeadlineRegex.java | 83 +++++++++++++++---- .../velocity/RenderLimitInsertionHandler.java | 5 +- .../rendering/velocity/RenderLimitParser.java | 5 +- .../velocity/RenderLimitUberspector.java | 4 + .../ui/rendering/velocity/StringGrowth.java | 6 +- .../ui/rendering/velocity/ValueLimits.java | 36 ++++++-- .../rendering/velocity/DeadlineRegexTest.java | 1 + .../rendering/velocity/RenderLimitsTest.java | 16 +++- .../rendering/velocity/StringGrowthTest.java | 13 +++ 9 files changed, 137 insertions(+), 32 deletions(-) diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java index 3084bacc33..45c8ed84da 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegex.java @@ -231,9 +231,7 @@ private static Pattern compile(String regex) { * empty followed by a quantifier, or a group with two alternatives that * can. Matching such an expression can try exponentially many ways * without reading a character, so DeadlineText never gets to check the - * deadline. Whether a part can match empty is tried with Pattern itself, - * on a few short texts; a part that doesn't compile on its own counts as - * one that can. + * deadline. See canMatchEmpty for how a part is tried. */ static void checkPattern(String regex) { // for each open group: where its body and its current alternative @@ -289,25 +287,82 @@ static void checkPattern(String regex) { } } - /** Short texts to try whether part of an expression can match empty in them. */ - private static final String[] EMPTY_MATCH_TEXTS = {"", "a", "a b", "\n", "0_"}; - + /** + * @return true if part of an expression can match an empty string. + * Lookarounds, anchors and boundaries match empty somewhere + * whatever they test, so they are taken out first, and the part + * is tried with and without comments mode, which an inline (?x) + * may have turned on. A part that doesn't compile on its own + * counts as one that can. + */ private static boolean canMatchEmpty(String part) { - Pattern p; + String rest = withoutZeroWidth(part); try { - p = Pattern.compile(part); + return Pattern.compile(rest).matcher("").matches() + || Pattern.compile(rest, Pattern.COMMENTS).matcher("").matches(); } catch (RuntimeException ex) { return true; } - for (String text : EMPTY_MATCH_TEXTS) { - Matcher m = p.matcher(text).useTransparentBounds(true).useAnchoringBounds(false); - for (int at = 0; at <= text.length(); at++) { - if (m.region(at, at).matches()) { - return true; + } + + /** @return the part with its lookarounds, anchors and boundaries taken out */ + private static String withoutZeroWidth(String part) { + StringBuilder out = new StringBuilder(); + int n = part.length(); + int i = 0; + while (i < n) { + char c = part.charAt(i); + if (c == '\\') { + char e = i + 1 < n ? part.charAt(i + 1) : 0; + int end = e == 'Q' ? skipEscape(part, i) : Math.min(i + 2, n); + if ("bBAGzZ".indexOf(e) < 0 || e == 0) { + out.append(part, i, end); } + i = end; + } else if (c == '[') { + int end = skipClass(part, i); + out.append(part, i, end); + i = end; + } else if (c == '^' || c == '$') { + i++; + } else if (c == '(' && isLookaround(part, i)) { + out.append("(?:)"); + i = closingParen(part, i) + 1; + } else { + out.append(c); + i++; } } - return false; + return out.toString(); + } + + private static boolean isLookaround(String regex, int i) { + return regex.startsWith("(?=", i) || regex.startsWith("(?!", i) + || regex.startsWith("(?<=", i) || regex.startsWith("(? entry = (Map.Entry) value; + long key = textLength(entry.getKey(), limit); + return key > limit ? key : 1 + key + textLength(entry.getValue(), limit - key); + } if (!isContainer(value)) { return leafLength(value); } @@ -110,6 +115,11 @@ private static long visit(Object item, Frame walk, Deque walks) { walks.push(new Frame(item)); return 2; } + if (item instanceof Map.Entry) { + // key=value, as a map's entries print + Map.Entry entry = (Map.Entry) item; + return 1 + visit(entry.getKey(), walk, walks) + visit(entry.getValue(), walk, walks); + } return leafLength(item); } @@ -117,6 +127,11 @@ private static boolean isContainer(Object value) { return value instanceof Collection || value instanceof Map; } + /** @return true if the value's text is built from a list or map it holds */ + static boolean holdsValues(Object value) { + return isContainer(value) || value instanceof Map.Entry; + } + private static long leafLength(Object value) { return value instanceof CharSequence ? ((CharSequence) value).length() : String.valueOf(value).length(); @@ -131,18 +146,21 @@ static long size(Object value) { } /** - * Checks a call on a list or map before it runs: the items it may add - * from the lists and maps passed to it have to fit the render's budget, - * a comparison of every element with every other has to stay small, and - * the text of toString has to fit the output limit. + * Checks a call on a list or map before it runs: the items addAll or + * putAll may add, or toArray or clone may copy, have to fit the render's + * budget, a comparison of every element with every other has to stay + * small, and the text of toString has to fit the output limit. */ static void checkContainerCall(Object receiver, String methodName, Object[] args, long maxChars) { long receiverSize = size(receiver); + boolean adds = "addAll".equals(methodName) || "putAll".equals(methodName); long added = 0; for (Object arg : args) { long argSize = size(arg); - added += argSize; + if (adds) { + added += argSize; + } boolean compares = "containsAll".equals(methodName) && !(receiver instanceof Set) || ("removeAll".equals(methodName) || "retainAll".equals(methodName)) && !(arg instanceof Set); @@ -151,12 +169,20 @@ static void checkContainerCall(Object receiver, String methodName, Object[] args + MAX_COMPARISONS + " pairs of elements"); } } + if (isCopy(methodName)) { + added += receiverSize; + } RenderSession.checkItems(added); if ("toString".equals(methodName) && args.length == 0) { RenderSession.checkLength(textLength(receiver, maxChars)); } } + /** @return true for the calls that return a copy of a list or map's items */ + static boolean isCopy(String methodName) { + return "toArray".equals(methodName) || "clone".equals(methodName); + } + /** * Checks a call on a big number before it runs, for the calls whose * result can be far larger than the number: pow, the shifts and the bit diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegexTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegexTest.java index 63f0a24db2..865d17582f 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegexTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/DeadlineRegexTest.java @@ -46,6 +46,7 @@ void refusesExpressionsThatRepeatAnEmptyMatch() { String[] refused = { "(?:a?|b?)c", "(|)z", "(?:)*", "x(?:(?:)?){3}", "\\b*", "(?=)+", "^?a", "()\\1*", "(?:(?:a|){2})", "(?a*|b*)", "(?i:x?|y?)", "((a)|(b)?|c*)d", + "(?:(?<=k)|(? DeadlineRegex.checkPattern(regex), 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 index 24d8f7102f..f42faea7eb 100644 --- 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 @@ -495,6 +495,8 @@ public void aLargeListIsRefusedBeforeItIsWrittenAsText() throws Exception { "#set($s = 'x')$s.valueOf($r)", "#if($r == 'x')yes#end", "#set($m = {'k': $r})$m", + "#set($m = {'k': $r})$m.entrySet()", + "#set($m = {'k': $r})#foreach($e in $m.entrySet())$e#end", }; for (int i = 0; i < uses.length; i++) { Outcome outcome = renderWithLimit("limits-list-text-" + i + ".vm", @@ -522,14 +524,24 @@ public void smallListsAndMapsStillPrint() throws Exception { @Test public void aTemplateThatBuildsAHugeListStopsAtTheLimit() throws Exception { Outcome doubled = render("limits-list-doubling.vm", - "#set($l = [1])#foreach($i in [1..24])#set($x = $l.addAll($l))#end$l.size()"); + "#set($l = [1])#foreach($i in [1..21])#set($x = $l.addAll($l))#end$l.size()"); assertLimit(doubled, "rendering added more than 1000000 items"); // the range is refused before any of it is copied Outcome copied = render("limits-list-copy.vm", - "#set($l = [])#set($x = $l.addAll([1..30000000]))$l.size()"); + "#set($l = [])#set($x = $l.addAll([1..1000001]))$l.size()"); assertLimit(copied, "rendering added more than 1000000 items"); + Outcome array = render("limits-list-array.vm", + "#set($r = [1..1000001])#set($a = $r.toArray())$a.size()"); + assertLimit(array, "rendering added more than 1000000 items"); + + // adding a large list as one item is one item + Outcome one = render("limits-list-one.vm", + "#set($l = [])#set($x = $l.add([1..2000000]))$l.size() ${l.get(0).size()}"); + assertEquals(null, one.failure); + assertEquals("1 2000000", one.out.getHead()); + Outcome map = render("limits-map.vm", "#set($m = {})#foreach($i in [1..1000])#foreach($j in [1..1001])" + "#set($x = $m.put(\"$i-$j\", $j))#end#end$m.size()"); diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java index c2506f686b..4ca7ea08ea 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/velocity/StringGrowthTest.java @@ -284,6 +284,19 @@ void utilitiesReplaceIsExact() { new Object[] {"a.a", "", "xyzw"})); } + /** A list appended as an Object is printed in full, so it counts as its text. */ + @Test + void appendingAListCountsItsText() { + java.util.List list = new ArrayList<>(); + for (int i = 0; i < 1000; i++) { + list.add(i); + } + StringBuilder b = new StringBuilder("x"); + long bound = StringGrowth.maxResultLength(b, "append", new Object[] {list}); + assertTrue(bound >= 1 + list.toString().length(), "bound was " + bound); + assertTrue(StringGrowth.maxResultLength(b, "append", new Object[] {null}) >= 5); + } + @Test void builderGrowthIsBounded() { StringBuilder b = new StringBuilder("abc");