From 8032cff8832b2929aee7491281c836d7c38a0951 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Tue, 17 Nov 2026 16:35:21 -0700 Subject: [PATCH 01/10] Take the site URL from setup, not from the first request When site.absoluteurl is empty, the installer's bootstrap step and the registration of the first administrator now save it from that request (scheme, host, port and context path). InitFilter no longer stores a request-derived absolute URL for the whole application. Instead it makes each request's URL available on its own thread for the length of that request, and getAbsoluteContextURL() falls back to it only while site.absoluteurl is unset, logging a warning once. Page, feed, site-wide and planet output that used the request's URL is not added to the rendering caches. The request URL now uses the request's scheme and keeps non-default ports, so HTTPS sites get https:// links. --- .../config/WebloggerRuntimeConfig.java | 95 ++++++++-- .../weblogger/ui/core/filters/InitFilter.java | 111 +++++------- .../ui/rendering/util/cache/PlanetCache.java | 8 + .../rendering/util/cache/SiteWideCache.java | 7 + .../rendering/util/cache/WeblogFeedCache.java | 8 + .../rendering/util/cache/WeblogPageCache.java | 8 + .../weblogger/ui/struts2/core/Install.java | 19 ++ .../weblogger/ui/struts2/core/Register.java | 11 +- .../ui/core/filters/InitFilterTest.java | 166 +++++++++++++++--- .../ui/struts2/core/InstallTest.java | 59 +++++++ .../ui/struts2/core/RegisterSiteUrlTest.java | 149 ++++++++++++++++ 11 files changed, 540 insertions(+), 101 deletions(-) create mode 100644 app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/RegisterSiteUrlTest.java diff --git a/app/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java b/app/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java index 1417ecb9c..2b44faa73 100644 --- a/app/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java +++ b/app/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java @@ -22,11 +22,13 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; +import java.util.concurrent.atomic.AtomicBoolean; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.roller.util.RollerConstants; import org.apache.roller.weblogger.config.runtime.RuntimeConfigDefs; import org.apache.roller.weblogger.config.runtime.RuntimeConfigDefsParser; +import org.apache.roller.weblogger.WebloggerException; import org.apache.roller.weblogger.business.PropertiesManager; import org.apache.roller.weblogger.business.WebloggerFactory; import org.apache.roller.weblogger.pojos.RuntimeConfigProperty; @@ -49,7 +51,15 @@ public final class WebloggerRuntimeConfig { // special case for our context urls private static String relativeContextURL = null; - private static String absoluteContextURL = null; + + // absolute url derived from the request being handled on this thread, used + // only while site.absoluteurl is unset and never kept past that request + private static final ThreadLocal requestAbsoluteContextURL = + new ThreadLocal<>(); + private static final ThreadLocal requestAbsoluteContextURLUsed = + new ThreadLocal<>(); + private static final AtomicBoolean absoluteURLWarningLogged = + new AtomicBoolean(false); // prevent instantiations @@ -169,21 +179,44 @@ public static String getRuntimeConfigDefsAsString() { /** - * Special method which sets the non-persisted absolute url to this site. + * Set the absolute url of the request being handled on this thread. The + * InitFilter sets this at the start of each request and clears it with + * clearRequestAbsoluteContextURL() when the request is done. * - * This property is *not* persisted in any way. + * This value is *not* persisted or shared with other threads. */ - public static void setAbsoluteContextURL(String url) { - absoluteContextURL = url; + public static void setRequestAbsoluteContextURL(String url) { + requestAbsoluteContextURL.set(url); + requestAbsoluteContextURLUsed.remove(); } - - + + + /** + * Forget the absolute url of the request handled on this thread. + */ + public static void clearRequestAbsoluteContextURL() { + requestAbsoluteContextURL.remove(); + requestAbsoluteContextURLUsed.remove(); + } + + + /** + * True if getAbsoluteContextURL() has returned the current request's url + * on this thread. Output built from that url depends on the request's Host + * header, so the rendering caches don't store it. + */ + public static boolean isRequestAbsoluteContextURLUsed() { + return Boolean.TRUE.equals(requestAbsoluteContextURLUsed.get()); + } + + /** * Get the absolute url to this site. * * This method will just return the value of the "site.absoluteurl" - * property if it is set, otherwise it will return the non-persisted - * value which is set by the InitFilter. + * property if it is set. Otherwise it returns the url of the request + * being handled on this thread, or null when there is no such request + * (for example in background tasks). */ public static String getAbsoluteContextURL() { @@ -192,8 +225,48 @@ public static String getAbsoluteContextURL() { if(absURL != null && !absURL.isBlank()) { return absURL; } - - return absoluteContextURL; + + if (absoluteURLWarningLogged.compareAndSet(false, true)) { + log.warn("The site's absolute URL (site.absoluteurl) is not set, so " + + "links in emails and feeds will use the host name of each " + + "request. Set \"Absolute URL to site\" under Server " + + "Administration > Configuration."); + } + + String requestURL = requestAbsoluteContextURL.get(); + if (requestURL != null) { + requestAbsoluteContextURLUsed.set(Boolean.TRUE); + } + return requestURL; + } + + + /** + * Save the given url as site.absoluteurl if that property is empty. + * Called when the site is being set up, by the installer and by the + * registration of the first administrator. + * + * @return true if the url was saved; the caller must flush + */ + public static boolean saveAbsoluteContextURLIfUnset(String url) + throws WebloggerException { + + if (url == null || url.isBlank()) { + return false; + } + PropertiesManager pmgr = WebloggerFactory.getWeblogger().getPropertiesManager(); + RuntimeConfigProperty prop = pmgr.getProperty("site.absoluteurl"); + if (prop != null && prop.getValue() != null && !prop.getValue().isBlank()) { + return false; + } + if (prop == null) { + prop = new RuntimeConfigProperty("site.absoluteurl", url); + } else { + prop.setValue(url); + } + pmgr.saveProperty(prop); + log.info("Set site.absoluteurl to " + url); + return true; } diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/filters/InitFilter.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/filters/InitFilter.java index 6ebbba485..de9befc95 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/filters/InitFilter.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/filters/InitFilter.java @@ -20,6 +20,7 @@ package org.apache.roller.weblogger.ui.core.filters; import java.io.IOException; +import java.util.Locale; import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; @@ -35,9 +36,14 @@ import org.apache.roller.weblogger.config.WebloggerRuntimeConfig; /** - * A special initialization filter which ensures that we have an opportunity to - * extract a few pieces of information about the environment we are running in - * when the first request is sent. + * A special initialization filter which records a few pieces of information + * about the environment we are running in. + * + * The relative context url is taken from the first request. The absolute url + * of each request is made available to WebloggerRuntimeConfig for the length + * of that request only, so it can stand in for site.absoluteurl while that + * property is unset. It is never stored beyond the request, because it comes + * from the client's Host header. * * @web.filter name="InitFilter" */ @@ -45,48 +51,38 @@ public class InitFilter implements Filter { private static final Log log = LogFactory.getLog(InitFilter.class); - private boolean initialized = false; + private static final UrlValidator URL_VALIDATOR = new UrlValidator( + new String[]{"http", "https"}, + UrlValidator.ALLOW_LOCAL_URLS); // for integration tests + + private volatile boolean initialized = false; @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { - if (!initialized) { + HttpServletRequest request = (HttpServletRequest) req; + String absPath = getAbsoluteUrl(request); + + if (!initialized && absPath != null) { // first request, lets do our initialization - HttpServletRequest request = (HttpServletRequest) req; - - UrlValidator validator = new UrlValidator( - new String[]{"http", "https"}, - UrlValidator.ALLOW_LOCAL_URLS); // for integration tests - - if(validator.isValid(request.getRequestURL().toString())) { - - // determine absolute and relative url paths to the app - String relPath = request.getContextPath(); - String absPath = this.getAbsoluteUrl(request); - - // set them in our config - WebloggerRuntimeConfig.setAbsoluteContextURL(absPath); - WebloggerRuntimeConfig.setRelativeContextURL(relPath); - - if (log.isDebugEnabled()) { - log.debug("relPath = " + relPath); - log.debug("absPath = " + absPath); - } - - this.initialized = true; + String relPath = request.getContextPath(); + WebloggerRuntimeConfig.setRelativeContextURL(relPath); + + if (log.isDebugEnabled()) { + log.debug("relPath = " + relPath); } + this.initialized = true; } - chain.doFilter(req, res); - } - - private String getAbsoluteUrl(HttpServletRequest request) { - return getAbsoluteUrl(request.isSecure(), - request.getServerName(), request.getContextPath(), - request.getRequestURI(), request.getRequestURL().toString()); + WebloggerRuntimeConfig.setRequestAbsoluteContextURL(absPath); + try { + chain.doFilter(req, res); + } finally { + WebloggerRuntimeConfig.clearRequestAbsoluteContextURL(); + } } @Override @@ -97,42 +93,31 @@ public void init(FilterConfig filterConfig) throws ServletException { public void destroy() { } - protected static String getAbsoluteUrl(boolean secure, String serverName, String contextPath, String requestURI, String requestURL){ + /** + * The absolute url of the application as seen by this request: scheme, + * host, port (when not the scheme's default) and context path. Returns + * null if the request url is not a valid http or https url. + */ + public static String getAbsoluteUrl(HttpServletRequest request) { - String url; - - String fullUrl; - - if (!secure) { - fullUrl = requestURL; - } else { - fullUrl = "http://" + serverName + contextPath; + if (!URL_VALIDATOR.isValid(request.getRequestURL().toString())) { + return null; } - // if the uri is only "/" then we are basically done - if ("/".equals(requestURI)) { - if (log.isDebugEnabled()) { - log.debug("requestURI is only '/'. fullUrl: " + fullUrl); - } - return removeTrailingSlash(fullUrl); - } - - // find first "/" starting after hostname is specified - int index = fullUrl.indexOf('/', - fullUrl.indexOf(serverName)); + String scheme = request.getScheme().toLowerCase(Locale.ROOT); + int port = request.getServerPort(); - if (index != -1) { - // extract just the part leading up to uri - url = fullUrl.substring(0, index); - } else { - url = fullUrl.trim(); + StringBuilder url = new StringBuilder(scheme) + .append("://").append(request.getServerName()); + boolean defaultPort = ("http".equals(scheme) && port == 80) + || ("https".equals(scheme) && port == 443); + if (port > 0 && !defaultPort) { + url.append(':').append(port); } - - // then just add on the context path - url += contextPath; + url.append(request.getContextPath()); // make certain that we don't end with a / - return removeTrailingSlash(url); + return removeTrailingSlash(url.toString()); } protected static String removeTrailingSlash(String url) { diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/PlanetCache.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/PlanetCache.java index 2c48e408f..2d8b942b0 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/PlanetCache.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/PlanetCache.java @@ -27,6 +27,7 @@ import org.apache.commons.logging.LogFactory; import org.apache.roller.util.RollerConstants; import org.apache.roller.weblogger.config.WebloggerConfig; +import org.apache.roller.weblogger.config.WebloggerRuntimeConfig; import org.apache.roller.weblogger.ui.rendering.util.PlanetRequest; import org.apache.roller.weblogger.util.cache.Cache; import org.apache.roller.weblogger.util.cache.CacheManager; @@ -120,6 +121,13 @@ public void put(String key, Object value) { if (!cacheEnabled) { return; } + + // links in this content were built from the request's host because + // site.absoluteurl is unset, so it isn't safe to serve to others + if (WebloggerRuntimeConfig.isRequestAbsoluteContextURLUsed()) { + log.debug("NOT CACHED, uses request host "+key); + return; + } contentCache.put(key, value); log.debug("PUT "+key); diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/SiteWideCache.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/SiteWideCache.java index f6b4dc71e..f78f12c42 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/SiteWideCache.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/SiteWideCache.java @@ -126,6 +126,13 @@ public void put(String key, Object value) { if (!cacheEnabled) { return; } + + // links in this content were built from the request's host because + // site.absoluteurl is unset, so it isn't safe to serve to others + if (WebloggerRuntimeConfig.isRequestAbsoluteContextURLUsed()) { + log.debug("NOT CACHED, uses request host "+key); + return; + } contentCache.put(key, value); log.debug("PUT "+key); diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogFeedCache.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogFeedCache.java index 6810518d5..5f4e4e764 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogFeedCache.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogFeedCache.java @@ -28,6 +28,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.roller.weblogger.config.WebloggerConfig; +import org.apache.roller.weblogger.config.WebloggerRuntimeConfig; import org.apache.roller.weblogger.ui.rendering.util.WeblogFeedRequest; import org.apache.roller.weblogger.util.Utilities; import org.apache.roller.weblogger.util.cache.Cache; @@ -120,6 +121,13 @@ public void put(String key, Object value) { if (!cacheEnabled) { return; } + + // links in this content were built from the request's host because + // site.absoluteurl is unset, so it isn't safe to serve to others + if (WebloggerRuntimeConfig.isRequestAbsoluteContextURLUsed()) { + log.debug("NOT CACHED, uses request host "+key); + return; + } contentCache.put(key, new LazyExpiringCacheEntry(value)); log.debug("PUT "+key); diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogPageCache.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogPageCache.java index 0fce6b73a..63c3e98b6 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogPageCache.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogPageCache.java @@ -28,6 +28,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.roller.weblogger.config.WebloggerConfig; +import org.apache.roller.weblogger.config.WebloggerRuntimeConfig; import org.apache.roller.weblogger.ui.rendering.util.WeblogPageRequest; import org.apache.roller.weblogger.util.Utilities; import org.apache.roller.weblogger.util.cache.Cache; @@ -118,6 +119,13 @@ public void put(String key, Object value) { if (!cacheEnabled) { return; } + + // links in this content were built from the request's host because + // site.absoluteurl is unset, so it isn't safe to serve to others + if (WebloggerRuntimeConfig.isRequestAbsoluteContextURLUsed()) { + log.debug("NOT CACHED, uses request host "+key); + return; + } contentCache.put(key, new LazyExpiringCacheEntry(value)); log.debug("PUT "+key); diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Install.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Install.java index e270ef4c2..f0f2ecb34 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Install.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Install.java @@ -31,8 +31,10 @@ import org.apache.roller.weblogger.business.startup.StartupException; import org.apache.roller.weblogger.business.startup.WebloggerStartup; import org.apache.roller.weblogger.config.WebloggerConfig; +import org.apache.roller.weblogger.config.WebloggerRuntimeConfig; import org.apache.roller.weblogger.ui.struts2.util.UIAction; import org.springframework.beans.FatalBeanException; +import org.apache.roller.weblogger.ui.core.filters.InitFilter; import org.apache.roller.weblogger.ui.core.security.BootstrapSecurity; @@ -178,6 +180,10 @@ public String bootstrap() { // installer reachable until the next restart. BootstrapSecurity.completeIfInstalled(WebloggerFactory.getWeblogger()); + // whoever runs the installer is setting up the site, so take the + // site's url from this request if none is configured + saveSiteUrlIfUnset(); + // also need to do planet if it's configured if (WebloggerConfig.getBooleanProperty("planet.aggregator.enabled")) { @@ -208,6 +214,19 @@ public String bootstrap() { } + private void saveSiteUrlIfUnset() { + try { + if (WebloggerRuntimeConfig.saveAbsoluteContextURLIfUnset( + InitFilter.getAbsoluteUrl(getServletRequest()))) { + WebloggerFactory.getWeblogger().flush(); + } + } catch (Exception e) { + log.warn("Could not save site.absoluteurl; set it under Server " + + "Administration > Configuration", e); + } + } + + public String getDatabaseProductName() { String name = "unknown"; diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Register.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Register.java index cf8fc87e0..cb80f817b 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Register.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Register.java @@ -36,6 +36,7 @@ import org.apache.roller.weblogger.pojos.User; import org.apache.roller.weblogger.pojos.RuntimeConfigProperty; import org.apache.roller.weblogger.ui.core.RollerSession; +import org.apache.roller.weblogger.ui.core.filters.InitFilter; import org.apache.roller.weblogger.ui.core.security.CustomUserRegistry; import org.apache.roller.weblogger.ui.core.security.BootstrapSecurity; import org.apache.roller.weblogger.ui.struts2.util.UIAction; @@ -197,7 +198,8 @@ public String save() { if (!hasActionErrors()) { try { - if (!BootstrapSecurity.isCompleted()) BootstrapSecurity.beginInitialAdmin(); + boolean initialAdmin = !BootstrapSecurity.isCompleted(); + if (initialAdmin) BootstrapSecurity.beginInitialAdmin(); UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); @@ -242,6 +244,13 @@ public String save() { WebloggerFactory.getWeblogger().getPropertiesManager().saveProperty( new RuntimeConfigProperty(BootstrapSecurity.COMPLETION_PROPERTY, "true")); + // the first administrator is the one setting up the site, so + // take the site's url from this request if none is configured + if (initialAdmin) { + WebloggerRuntimeConfig.saveAbsoluteContextURLIfUnset( + InitFilter.getAbsoluteUrl(getServletRequest())); + } + WebloggerFactory.getWeblogger().flush(); if (!BootstrapSecurity.isCompleted()) BootstrapSecurity.complete(); diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/InitFilterTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/InitFilterTest.java index d5b0ba753..4fe2d451f 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/InitFilterTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/InitFilterTest.java @@ -19,9 +19,30 @@ package org.apache.roller.weblogger.ui.core.filters; +import java.util.concurrent.atomic.AtomicReference; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +import org.apache.roller.weblogger.business.PropertiesManager; +import org.apache.roller.weblogger.business.Weblogger; +import org.apache.roller.weblogger.business.WebloggerFactory; +import org.apache.roller.weblogger.config.WebloggerRuntimeConfig; +import org.apache.roller.weblogger.ui.rendering.util.cache.SiteWideCache; +import org.apache.roller.weblogger.ui.rendering.util.cache.WeblogFeedCache; +import org.apache.roller.weblogger.ui.rendering.util.cache.WeblogPageCache; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; /** @@ -31,48 +52,141 @@ public class InitFilterTest { private static final String SERVER_NAME = "roller.example.com"; + private MockedStatic factory; + + /** + * Run with an empty site.absoluteurl, so getAbsoluteContextURL() has to + * fall back to whatever the request supplies. + */ + @BeforeEach + public void setUp() { + Weblogger weblogger = mock(Weblogger.class); + when(weblogger.getPropertiesManager()).thenReturn(mock(PropertiesManager.class)); + factory = mockStatic(WebloggerFactory.class); + factory.when(WebloggerFactory::getWeblogger).thenReturn(weblogger); + } + + @AfterEach + public void tearDown() { + factory.close(); + } + + static HttpServletRequest request(String scheme, String host, int port, + String contextPath, String uri) { + HttpServletRequest request = mock(HttpServletRequest.class); + boolean defaultPort = ("http".equals(scheme) && port == 80) + || ("https".equals(scheme) && port == 443); + String url = scheme + "://" + host + (defaultPort ? "" : ":" + port) + uri; + when(request.getScheme()).thenReturn(scheme); + when(request.isSecure()).thenReturn("https".equals(scheme)); + when(request.getServerName()).thenReturn(host); + when(request.getServerPort()).thenReturn(port); + when(request.getContextPath()).thenReturn(contextPath); + when(request.getRequestURI()).thenReturn(uri); + when(request.getRequestURL()).thenReturn(new StringBuffer(url)); + return request; + } + + /** The absolute URL getAbsoluteContextURL() returns while handling it. */ + private static String urlDuring(InitFilter filter, HttpServletRequest request) + throws Exception { + AtomicReference seen = new AtomicReference<>(); + FilterChain chain = (req, res) -> + seen.set(WebloggerRuntimeConfig.getAbsoluteContextURL()); + filter.doFilter(request, mock(HttpServletResponse.class), chain); + return seen.get(); + } + @Test public void testGetAbsoluteUrlOnRootWithHttp() throws Exception { - boolean secure = false; - String contextPath = ""; - String requestURI = "/"; - String requestURL = "http://roller.example.com/"; - - String absoluteUrl = InitFilter.getAbsoluteUrl(secure, SERVER_NAME, contextPath, requestURI, requestURL); - assertEquals("http://roller.example.com", absoluteUrl); + assertEquals("http://roller.example.com", urlDuring(new InitFilter(), + request("http", SERVER_NAME, 80, "", "/"))); } @Test public void testGetAbsoluteUrlOnRootWithHttps() throws Exception { - boolean secure = true; - String contextPath = ""; - String requestURI = "/"; - String requestURL = "https://roller.example.com/"; + assertEquals("https://roller.example.com", urlDuring(new InitFilter(), + request("https", SERVER_NAME, 443, "", "/"))); + } - String absoluteUrl = InitFilter.getAbsoluteUrl(secure, SERVER_NAME, contextPath, requestURI, requestURL); - assertEquals("http://roller.example.com", absoluteUrl); + @Test + public void testGetAbsoluteUrlWithHttpsOnOtherPort() throws Exception { + assertEquals("https://roller.example.com:8443/roller", urlDuring(new InitFilter(), + request("https", SERVER_NAME, 8443, "/roller", "/roller/handle/"))); } @Test - public void testGetAbsoluteUrlAgainstTop() throws Exception { - boolean secure = false; - String contextPath = "/roller"; - String requestURI = "/roller/"; - String requestURL = "http://roller.example.com/roller/"; + public void testGetAbsoluteUrlWithHttpOnOtherPort() throws Exception { + assertEquals("http://roller.example.com:8080/roller", urlDuring(new InitFilter(), + request("http", SERVER_NAME, 8080, "/roller", "/roller/"))); + } - String absoluteUrl = InitFilter.getAbsoluteUrl(secure, SERVER_NAME, contextPath, requestURI, requestURL); - assertEquals("http://roller.example.com/roller", absoluteUrl); + @Test + public void testGetAbsoluteUrlAgainstTop() throws Exception { + assertEquals("http://roller.example.com/roller", urlDuring(new InitFilter(), + request("http", SERVER_NAME, 80, "/roller", "/roller/"))); } @Test public void testGetAbsoluteUrlAgainstPermalink() throws Exception { - boolean secure = false; - String contextPath = "/roller"; - String requestURI = "/roller/handle/entry/title"; - String requestURL = "http://roller.example.com/roller/handle/entry/title"; + assertEquals("http://roller.example.com/roller", urlDuring(new InitFilter(), + request("http", SERVER_NAME, 80, "/roller", "/roller/handle/entry/title"))); + } - String absoluteUrl = InitFilter.getAbsoluteUrl(secure, SERVER_NAME, contextPath, requestURI, requestURL); - assertEquals("http://roller.example.com/roller", absoluteUrl); + /** + * Each request sees its own host, and nothing is left behind once the + * request has been handled. + */ + @Test + public void testRequestHostIsNotKeptAfterTheRequest() throws Exception { + InitFilter filter = new InitFilter(); + assertEquals("http://first.example.com", urlDuring(filter, + request("http", "first.example.com", 80, "", "/"))); + assertNull(WebloggerRuntimeConfig.getAbsoluteContextURL(), + "a request's host must not outlive the request"); + assertEquals("http://second.example.com", urlDuring(filter, + request("http", "second.example.com", 80, "", "/"))); + assertNull(WebloggerRuntimeConfig.getAbsoluteContextURL()); + } + + /** + * Content rendered with a URL taken from the request must not be stored + * in the shared caches, where other visitors would be served it. + */ + @Test + public void testContentBuiltFromRequestHostIsNotCached() throws Exception { + String key = "InitFilterTest/" + System.nanoTime(); + FilterChain chain = (req, res) -> { + String url = WebloggerRuntimeConfig.getAbsoluteContextURL(); + WeblogPageCache.getInstance().put(key, url); + WeblogFeedCache.getInstance().put(key, url); + SiteWideCache.getInstance().put(key, url); + }; + try { + new InitFilter().doFilter(request("http", "other.example.com", 80, "", "/"), + mock(HttpServletResponse.class), chain); + assertNull(WeblogPageCache.getInstance().get(key, 0)); + assertNull(WeblogFeedCache.getInstance().get(key, 0)); + assertNull(SiteWideCache.getInstance().get(key)); + } finally { + WeblogPageCache.getInstance().remove(key); + WeblogFeedCache.getInstance().remove(key); + SiteWideCache.getInstance().remove(key); + } + } + + /** Caching is unaffected for content that did not use the request host. */ + @Test + public void testOtherContentIsStillCached() throws Exception { + String key = "InitFilterTest/" + System.nanoTime(); + FilterChain chain = (req, res) -> WeblogPageCache.getInstance().put(key, "page"); + try { + new InitFilter().doFilter(request("http", SERVER_NAME, 80, "", "/"), + mock(HttpServletResponse.class), chain); + assertNotNull(WeblogPageCache.getInstance().get(key, 0)); + } finally { + WeblogPageCache.getInstance().remove(key); + } } @Test diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/InstallTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/InstallTest.java index 22addc307..44cc30f52 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/InstallTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/InstallTest.java @@ -18,9 +18,17 @@ */ package org.apache.roller.weblogger.ui.struts2.core; +import java.util.List; +import java.util.stream.Collectors; +import jakarta.servlet.http.HttpServletRequest; +import org.apache.roller.weblogger.business.PropertiesManager; +import org.apache.roller.weblogger.business.Weblogger; import org.apache.roller.weblogger.business.WebloggerFactory; import org.apache.roller.weblogger.business.startup.*; +import org.apache.roller.weblogger.pojos.RuntimeConfigProperty; +import org.apache.roller.weblogger.ui.core.security.BootstrapSecurity; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import org.mockito.MockedStatic; import static org.mockito.Mockito.*; import static org.junit.jupiter.api.Assertions.*; @@ -40,4 +48,55 @@ void installerExposesItsTitleAndExceptionName() { assertEquals("java.lang.IllegalStateException", action.getRootCauseExceptionName()); } } + + /** + * The installer is run by the person setting the site up, so finishing it + * records the site's absolute URL from that request when none is set. + */ + @Test + void bootstrapRecordsSiteUrlWhenUnset() throws Exception { + assertEquals(List.of("https://blog.example.org:8443/roller"), + siteUrlsSavedByBootstrap(null)); + } + + @Test + void bootstrapKeepsConfiguredSiteUrl() throws Exception { + assertTrue(siteUrlsSavedByBootstrap("https://configured.example.org").isEmpty()); + } + + private static List siteUrlsSavedByBootstrap(String configured) throws Exception { + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getScheme()).thenReturn("https"); + when(request.isSecure()).thenReturn(true); + when(request.getServerName()).thenReturn("blog.example.org"); + when(request.getServerPort()).thenReturn(8443); + when(request.getContextPath()).thenReturn("/roller"); + when(request.getRequestURI()).thenReturn("/roller/roller-ui/install/install!bootstrap.rol"); + when(request.getRequestURL()).thenReturn(new StringBuffer( + "https://blog.example.org:8443/roller/roller-ui/install/install!bootstrap.rol")); + Install action = new Install(); + action.withServletRequest(request); + + PropertiesManager properties = mock(PropertiesManager.class); + if (configured != null) { + when(properties.getProperty("site.absoluteurl")) + .thenReturn(new RuntimeConfigProperty("site.absoluteurl", configured)); + } + Weblogger weblogger = mock(Weblogger.class); + when(weblogger.getPropertiesManager()).thenReturn(properties); + try (MockedStatic factory = mockStatic(WebloggerFactory.class); + MockedStatic bootstrap = mockStatic(BootstrapSecurity.class)) { + factory.when(WebloggerFactory::isBootstrapped).thenReturn(false); + factory.when(WebloggerFactory::getWeblogger).thenReturn(weblogger); + bootstrap.when(() -> BootstrapSecurity.isValid(any())).thenReturn(true); + assertEquals("success", action.bootstrap()); + } + ArgumentCaptor saved = + ArgumentCaptor.forClass(RuntimeConfigProperty.class); + verify(properties, atLeast(0)).saveProperty(saved.capture()); + return saved.getAllValues().stream() + .filter(p -> "site.absoluteurl".equals(p.getName())) + .map(RuntimeConfigProperty::getValue) + .collect(Collectors.toList()); + } } diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/RegisterSiteUrlTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/RegisterSiteUrlTest.java new file mode 100644 index 000000000..28e6aa51a --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/RegisterSiteUrlTest.java @@ -0,0 +1,149 @@ +/* + * 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.struts2.core; + +import java.util.List; +import java.util.stream.Collectors; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpSession; + +import org.apache.roller.weblogger.business.PropertiesManager; +import org.apache.roller.weblogger.business.UserManager; +import org.apache.roller.weblogger.business.Weblogger; +import org.apache.roller.weblogger.business.WebloggerFactory; +import org.apache.roller.weblogger.pojos.RuntimeConfigProperty; +import org.apache.roller.weblogger.ui.core.RollerContext; +import org.apache.roller.weblogger.ui.core.security.BootstrapSecurity; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import org.springframework.security.crypto.password.NoOpPasswordEncoder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * The administrator who registers first is the one setting the site up, so + * that registration records the site's absolute URL when none is configured. + * Later registrations never touch it. + */ +class RegisterSiteUrlTest { + + private MockedStatic factory; + private MockedStatic bootstrap; + private MockedStatic context; + private PropertiesManager properties; + + @BeforeEach + void setUp() throws Exception { + properties = mock(PropertiesManager.class); + UserManager users = mock(UserManager.class); + Weblogger weblogger = mock(Weblogger.class); + when(weblogger.getPropertiesManager()).thenReturn(properties); + when(weblogger.getUserManager()).thenReturn(users); + when(properties.getProperty("users.registration.enabled")) + .thenReturn(new RuntimeConfigProperty("users.registration.enabled", "true")); + + factory = mockStatic(WebloggerFactory.class); + factory.when(WebloggerFactory::getWeblogger).thenReturn(weblogger); + bootstrap = mockStatic(BootstrapSecurity.class); + context = mockStatic(RollerContext.class); + context.when(RollerContext::getPasswordEncoder) + .thenReturn(NoOpPasswordEncoder.getInstance()); + } + + @AfterEach + void tearDown() { + context.close(); + bootstrap.close(); + factory.close(); + } + + private static Register register(String scheme, String host, int port) { + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getScheme()).thenReturn(scheme); + when(request.isSecure()).thenReturn("https".equals(scheme)); + when(request.getServerName()).thenReturn(host); + when(request.getServerPort()).thenReturn(port); + when(request.getContextPath()).thenReturn("/roller"); + when(request.getRequestURI()).thenReturn("/roller/roller-ui/register!save.rol"); + when(request.getRequestURL()).thenReturn(new StringBuffer( + scheme + "://" + host + ":" + port + "/roller/roller-ui/register!save.rol")); + when(request.getSession()).thenReturn(mock(HttpSession.class)); + + Register action = new Register(); + action.withServletRequest(request); + action.getBean().setUserName("admin"); + action.getBean().setScreenName("Admin"); + action.getBean().setEmailAddress("admin@example.com"); + action.getBean().setPasswordText("s3cret-Passw0rd"); + action.getBean().setPasswordConfirm("s3cret-Passw0rd"); + return action; + } + + private List savedSiteUrls() throws Exception { + ArgumentCaptor saved = + ArgumentCaptor.forClass(RuntimeConfigProperty.class); + verify(properties, atLeast(0)).saveProperty(saved.capture()); + return saved.getAllValues().stream() + .filter(p -> "site.absoluteurl".equals(p.getName())) + .map(RuntimeConfigProperty::getValue) + .collect(Collectors.toList()); + } + + @Test + void firstAdministratorRecordsSiteUrl() throws Exception { + bootstrap.when(BootstrapSecurity::isCompleted).thenReturn(false); + bootstrap.when(() -> BootstrapSecurity.isValid(any())).thenReturn(true); + + assertEquals("success", register("https", "blog.example.org", 443).save()); + assertEquals(List.of("https://blog.example.org/roller"), savedSiteUrls()); + } + + @Test + void firstAdministratorKeepsConfiguredSiteUrl() throws Exception { + bootstrap.when(BootstrapSecurity::isCompleted).thenReturn(false); + bootstrap.when(() -> BootstrapSecurity.isValid(any())).thenReturn(true); + when(properties.getProperty("site.absoluteurl")).thenReturn( + new RuntimeConfigProperty("site.absoluteurl", "https://configured.example.org")); + + assertEquals("success", register("https", "blog.example.org", 443).save()); + assertTrue(savedSiteUrls().isEmpty(), "a configured URL must not be replaced"); + } + + @Test + void laterRegistrationsDoNotRecordSiteUrl() throws Exception { + bootstrap.when(BootstrapSecurity::isCompleted).thenReturn(true); + when(properties.getProperty("site.absoluteurl")) + .thenReturn(new RuntimeConfigProperty("site.absoluteurl", "")); + + assertEquals("success", register("http", "other.example.net", 80).save()); + assertTrue(savedSiteUrls().isEmpty(), + "only the initial administrator's registration may set the URL"); + } +} From 004413fceb3b58cb9d6e9675dc6c1241e536611b Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Tue, 17 Nov 2026 18:20:56 -0700 Subject: [PATCH 02/10] Cache pages per host while the site URL is unset, and save it from an admin's request While site.absoluteurl is unset, the page, feed, site-wide and planet caches now include the request's absolute URL in their keys instead of skipping the cache, so content built with one host name is only served to requests for that host name and caching keeps working. The first Roller UI request from a global administrator saves site.absoluteurl when it's still unset, which fills it in on sites upgraded without it. --- .../config/WebloggerRuntimeConfig.java | 46 ++++++-- .../ui/rendering/util/cache/PlanetCache.java | 10 +- .../rendering/util/cache/SiteWideCache.java | 10 +- .../rendering/util/cache/WeblogFeedCache.java | 10 +- .../rendering/util/cache/WeblogPageCache.java | 10 +- .../ui/struts2/util/UIActionInterceptor.java | 6 + .../weblogger/config/SiteUrlForAdminTest.java | 104 ++++++++++++++++++ .../ui/core/filters/InitFilterTest.java | 59 ++++++++-- 8 files changed, 205 insertions(+), 50 deletions(-) create mode 100644 app/src/test/java/org/apache/roller/weblogger/config/SiteUrlForAdminTest.java diff --git a/app/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java b/app/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java index 2b44faa73..1ff5cf03d 100644 --- a/app/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java +++ b/app/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java @@ -32,6 +32,7 @@ import org.apache.roller.weblogger.business.PropertiesManager; import org.apache.roller.weblogger.business.WebloggerFactory; import org.apache.roller.weblogger.pojos.RuntimeConfigProperty; +import org.apache.roller.weblogger.pojos.User; /** @@ -56,8 +57,6 @@ public final class WebloggerRuntimeConfig { // only while site.absoluteurl is unset and never kept past that request private static final ThreadLocal requestAbsoluteContextURL = new ThreadLocal<>(); - private static final ThreadLocal requestAbsoluteContextURLUsed = - new ThreadLocal<>(); private static final AtomicBoolean absoluteURLWarningLogged = new AtomicBoolean(false); @@ -187,7 +186,6 @@ public static String getRuntimeConfigDefsAsString() { */ public static void setRequestAbsoluteContextURL(String url) { requestAbsoluteContextURL.set(url); - requestAbsoluteContextURLUsed.remove(); } @@ -196,7 +194,6 @@ public static void setRequestAbsoluteContextURL(String url) { */ public static void clearRequestAbsoluteContextURL() { requestAbsoluteContextURL.remove(); - requestAbsoluteContextURLUsed.remove(); } @@ -205,8 +202,39 @@ public static void clearRequestAbsoluteContextURL() { * on this thread. Output built from that url depends on the request's Host * header, so the rendering caches don't store it. */ - public static boolean isRequestAbsoluteContextURLUsed() { - return Boolean.TRUE.equals(requestAbsoluteContextURLUsed.get()); + /** + * The cache key to use for content rendered for the current request. While + * site.absoluteurl is unset, links are built from the request's own URL, so + * the key includes it: content cached for one host name is only served to + * requests for that host name. + */ + public static String cacheKey(String key) { + String absURL = getProperty("site.absoluteurl"); + if (absURL != null && !absURL.isBlank()) { + return key; + } + String requestURL = requestAbsoluteContextURL.get(); + return requestURL == null ? key : key + "|" + requestURL; + } + + /** + * Saves site.absoluteurl from the current request when it is unset and the + * request comes from a global administrator, which is the case the first + * time an administrator opens the Roller UI after an upgrade. + */ + public static void saveAbsoluteContextURLForAdmin(User user) { + String absURL = getProperty("site.absoluteurl"); + if ((absURL != null && !absURL.isBlank()) || user == null + || !user.hasGlobalPermission("admin")) { + return; + } + try { + if (saveAbsoluteContextURLIfUnset(requestAbsoluteContextURL.get())) { + WebloggerFactory.getWeblogger().flush(); + } + } catch (WebloggerException e) { + log.warn("Could not save site.absoluteurl", e); + } } @@ -233,11 +261,7 @@ public static String getAbsoluteContextURL() { + "Administration > Configuration."); } - String requestURL = requestAbsoluteContextURL.get(); - if (requestURL != null) { - requestAbsoluteContextURLUsed.set(Boolean.TRUE); - } - return requestURL; + return requestAbsoluteContextURL.get(); } diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/PlanetCache.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/PlanetCache.java index 2d8b942b0..1a17ca19b 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/PlanetCache.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/PlanetCache.java @@ -99,6 +99,7 @@ public static PlanetCache getInstance() { public Object get(String key) { + key = WebloggerRuntimeConfig.cacheKey(key); if (!cacheEnabled) { return null; @@ -117,17 +118,11 @@ public Object get(String key) { public void put(String key, Object value) { + key = WebloggerRuntimeConfig.cacheKey(key); if (!cacheEnabled) { return; } - - // links in this content were built from the request's host because - // site.absoluteurl is unset, so it isn't safe to serve to others - if (WebloggerRuntimeConfig.isRequestAbsoluteContextURLUsed()) { - log.debug("NOT CACHED, uses request host "+key); - return; - } contentCache.put(key, value); log.debug("PUT "+key); @@ -135,6 +130,7 @@ public void put(String key, Object value) { public void remove(String key) { + key = WebloggerRuntimeConfig.cacheKey(key); if (!cacheEnabled) { return; diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/SiteWideCache.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/SiteWideCache.java index f78f12c42..eebbced19 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/SiteWideCache.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/SiteWideCache.java @@ -104,6 +104,7 @@ public static SiteWideCache getInstance() { public Object get(String key) { + key = WebloggerRuntimeConfig.cacheKey(key); if (!cacheEnabled) { return null; @@ -122,17 +123,11 @@ public Object get(String key) { public void put(String key, Object value) { + key = WebloggerRuntimeConfig.cacheKey(key); if (!cacheEnabled) { return; } - - // links in this content were built from the request's host because - // site.absoluteurl is unset, so it isn't safe to serve to others - if (WebloggerRuntimeConfig.isRequestAbsoluteContextURLUsed()) { - log.debug("NOT CACHED, uses request host "+key); - return; - } contentCache.put(key, value); log.debug("PUT "+key); @@ -140,6 +135,7 @@ public void put(String key, Object value) { public void remove(String key) { + key = WebloggerRuntimeConfig.cacheKey(key); if (!cacheEnabled) { return; diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogFeedCache.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogFeedCache.java index 5f4e4e764..ebc7f724a 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogFeedCache.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogFeedCache.java @@ -90,6 +90,7 @@ public static WeblogFeedCache getInstance() { public Object get(String key, long lastModified) { + key = WebloggerRuntimeConfig.cacheKey(key); if (!cacheEnabled) { return null; @@ -117,17 +118,11 @@ public Object get(String key, long lastModified) { public void put(String key, Object value) { + key = WebloggerRuntimeConfig.cacheKey(key); if (!cacheEnabled) { return; } - - // links in this content were built from the request's host because - // site.absoluteurl is unset, so it isn't safe to serve to others - if (WebloggerRuntimeConfig.isRequestAbsoluteContextURLUsed()) { - log.debug("NOT CACHED, uses request host "+key); - return; - } contentCache.put(key, new LazyExpiringCacheEntry(value)); log.debug("PUT "+key); @@ -135,6 +130,7 @@ public void put(String key, Object value) { public void remove(String key) { + key = WebloggerRuntimeConfig.cacheKey(key); if (!cacheEnabled) { return; diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogPageCache.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogPageCache.java index 63c3e98b6..0afddd336 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogPageCache.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogPageCache.java @@ -89,6 +89,7 @@ public static WeblogPageCache getInstance() { public Object get(String key, long lastModified) { + key = WebloggerRuntimeConfig.cacheKey(key); if (!cacheEnabled) { return null; @@ -115,17 +116,11 @@ public Object get(String key, long lastModified) { public void put(String key, Object value) { + key = WebloggerRuntimeConfig.cacheKey(key); if (!cacheEnabled) { return; } - - // links in this content were built from the request's host because - // site.absoluteurl is unset, so it isn't safe to serve to others - if (WebloggerRuntimeConfig.isRequestAbsoluteContextURLUsed()) { - log.debug("NOT CACHED, uses request host "+key); - return; - } contentCache.put(key, new LazyExpiringCacheEntry(value)); log.debug("PUT "+key); @@ -133,6 +128,7 @@ public void put(String key, Object value) { public void remove(String key) { + key = WebloggerRuntimeConfig.cacheKey(key); if (!cacheEnabled) { return; diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/util/UIActionInterceptor.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/util/UIActionInterceptor.java index 0a6682427..ac1733c0b 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/util/UIActionInterceptor.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/util/UIActionInterceptor.java @@ -25,6 +25,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.roller.weblogger.business.WebloggerFactory; +import org.apache.roller.weblogger.config.WebloggerRuntimeConfig; import org.apache.roller.weblogger.pojos.Weblog; import org.apache.roller.weblogger.ui.core.RollerSession; import org.apache.struts2.StrutsStatics; @@ -69,6 +70,11 @@ public String doIntercept(ActionInvocation invocation) throws Exception { RollerSession rses = RollerSession.getRollerSession(request); theAction.setAuthenticatedUser(rses != null ? rses.getAuthenticatedUser() : null); + // the first administrator request after an upgrade fills in an + // unset site.absoluteurl, so links and caching don't depend on + // the host of each request from then on + WebloggerRuntimeConfig.saveAbsoluteContextURLForAdmin(theAction.getAuthenticatedUser()); + // Set the action weblog by looking up the weblog handle. Always // overwrite (to null when no weblog resolves), so a value bound // from request parameters cannot survive. diff --git a/app/src/test/java/org/apache/roller/weblogger/config/SiteUrlForAdminTest.java b/app/src/test/java/org/apache/roller/weblogger/config/SiteUrlForAdminTest.java new file mode 100644 index 000000000..6bb6845fa --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/config/SiteUrlForAdminTest.java @@ -0,0 +1,104 @@ +/* + * 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.config; + +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.roller.weblogger.business.PropertiesManager; +import org.apache.roller.weblogger.business.Weblogger; +import org.apache.roller.weblogger.business.WebloggerFactory; +import org.apache.roller.weblogger.pojos.RuntimeConfigProperty; +import org.apache.roller.weblogger.pojos.User; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * The first request from a global administrator fills in an unset site URL. + */ +class SiteUrlForAdminTest { + + private MockedStatic factory; + private PropertiesManager properties; + + @BeforeEach + void setUp() { + properties = mock(PropertiesManager.class); + Weblogger weblogger = mock(Weblogger.class); + when(weblogger.getPropertiesManager()).thenReturn(properties); + factory = mockStatic(WebloggerFactory.class); + factory.when(WebloggerFactory::getWeblogger).thenReturn(weblogger); + WebloggerRuntimeConfig.setRequestAbsoluteContextURL("https://blog.example.org/roller"); + } + + @AfterEach + void tearDown() { + WebloggerRuntimeConfig.clearRequestAbsoluteContextURL(); + factory.close(); + } + + @Test + void anAdministratorsRequestSavesTheSiteUrl() throws Exception { + User admin = mock(User.class); + when(admin.hasGlobalPermission("admin")).thenReturn(true); + + WebloggerRuntimeConfig.saveAbsoluteContextURLForAdmin(admin); + + ArgumentCaptor saved = ArgumentCaptor.forClass(RuntimeConfigProperty.class); + verify(properties, atLeast(1)).saveProperty(saved.capture()); + List urls = saved.getAllValues().stream() + .filter(p -> "site.absoluteurl".equals(p.getName())) + .map(RuntimeConfigProperty::getValue).collect(Collectors.toList()); + assertEquals(List.of("https://blog.example.org/roller"), urls); + } + + @Test + void otherUsersDontSaveIt() throws Exception { + User editor = mock(User.class); + when(editor.hasGlobalPermission("admin")).thenReturn(false); + + WebloggerRuntimeConfig.saveAbsoluteContextURLForAdmin(editor); + WebloggerRuntimeConfig.saveAbsoluteContextURLForAdmin(null); + + verify(properties, never()).saveProperty(any()); + } + + @Test + void aConfiguredSiteUrlIsKept() throws Exception { + when(properties.getProperty("site.absoluteurl")).thenReturn( + new RuntimeConfigProperty("site.absoluteurl", "https://configured.example.org")); + User admin = mock(User.class); + when(admin.hasGlobalPermission("admin")).thenReturn(true); + + WebloggerRuntimeConfig.saveAbsoluteContextURLForAdmin(admin); + + verify(properties, never()).saveProperty(any()); + } +} diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/InitFilterTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/InitFilterTest.java index 4fe2d451f..9a3273189 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/InitFilterTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/InitFilterTest.java @@ -26,6 +26,7 @@ import jakarta.servlet.http.HttpServletResponse; import org.apache.roller.weblogger.business.PropertiesManager; +import org.apache.roller.weblogger.pojos.RuntimeConfigProperty; import org.apache.roller.weblogger.business.Weblogger; import org.apache.roller.weblogger.business.WebloggerFactory; import org.apache.roller.weblogger.config.WebloggerRuntimeConfig; @@ -154,9 +155,10 @@ public void testRequestHostIsNotKeptAfterTheRequest() throws Exception { * in the shared caches, where other visitors would be served it. */ @Test - public void testContentBuiltFromRequestHostIsNotCached() throws Exception { + public void testContentBuiltFromRequestHostIsCachedPerHost() throws Exception { String key = "InitFilterTest/" + System.nanoTime(); - FilterChain chain = (req, res) -> { + AtomicReference seen = new AtomicReference<>(); + FilterChain store = (req, res) -> { String url = WebloggerRuntimeConfig.getAbsoluteContextURL(); WeblogPageCache.getInstance().put(key, url); WeblogFeedCache.getInstance().put(key, url); @@ -164,28 +166,63 @@ public void testContentBuiltFromRequestHostIsNotCached() throws Exception { }; try { new InitFilter().doFilter(request("http", "other.example.com", 80, "", "/"), - mock(HttpServletResponse.class), chain); - assertNull(WeblogPageCache.getInstance().get(key, 0)); - assertNull(WeblogFeedCache.getInstance().get(key, 0)); - assertNull(SiteWideCache.getInstance().get(key)); + mock(HttpServletResponse.class), store); + + // the same host gets the cached content back + FilterChain sameHost = (req, res) -> seen.set(WeblogPageCache.getInstance().get(key, 0)); + new InitFilter().doFilter(request("http", "other.example.com", 80, "", "/"), + mock(HttpServletResponse.class), sameHost); + assertEquals("http://other.example.com", seen.get()); + + // another host doesn't + FilterChain otherHost = (req, res) -> seen.set(new Object[] { + WeblogPageCache.getInstance().get(key, 0), + WeblogFeedCache.getInstance().get(key, 0), + SiteWideCache.getInstance().get(key)}); + new InitFilter().doFilter(request("http", SERVER_NAME, 80, "", "/"), + mock(HttpServletResponse.class), otherHost); + Object[] others = (Object[]) seen.get(); + assertNull(others[0]); + assertNull(others[1]); + assertNull(others[2]); } finally { - WeblogPageCache.getInstance().remove(key); - WeblogFeedCache.getInstance().remove(key); - SiteWideCache.getInstance().remove(key); + FilterChain cleanup = (req, res) -> { + WeblogPageCache.getInstance().remove(key); + WeblogFeedCache.getInstance().remove(key); + SiteWideCache.getInstance().remove(key); + }; + new InitFilter().doFilter(request("http", "other.example.com", 80, "", "/"), + mock(HttpServletResponse.class), cleanup); } } + @Test + public void testCacheKeysIgnoreTheHostOnceTheSiteUrlIsSet() throws Exception { + PropertiesManager properties = WebloggerFactory.getWeblogger().getPropertiesManager(); + when(properties.getProperty("site.absoluteurl")).thenReturn( + new RuntimeConfigProperty("site.absoluteurl", "https://configured.example.org")); + AtomicReference key = new AtomicReference<>(); + new InitFilter().doFilter(request("http", "other.example.com", 80, "", "/"), + mock(HttpServletResponse.class), (req, res) -> key.set(WebloggerRuntimeConfig.cacheKey("k"))); + assertEquals("k", key.get()); + } + /** Caching is unaffected for content that did not use the request host. */ @Test public void testOtherContentIsStillCached() throws Exception { String key = "InitFilterTest/" + System.nanoTime(); FilterChain chain = (req, res) -> WeblogPageCache.getInstance().put(key, "page"); + AtomicReference seen = new AtomicReference<>(); + FilterChain lookup = (req, res) -> seen.set(WeblogPageCache.getInstance().get(key, 0)); try { new InitFilter().doFilter(request("http", SERVER_NAME, 80, "", "/"), mock(HttpServletResponse.class), chain); - assertNotNull(WeblogPageCache.getInstance().get(key, 0)); + new InitFilter().doFilter(request("http", SERVER_NAME, 80, "", "/"), + mock(HttpServletResponse.class), lookup); + assertNotNull(seen.get()); } finally { - WeblogPageCache.getInstance().remove(key); + new InitFilter().doFilter(request("http", SERVER_NAME, 80, "", "/"), + mock(HttpServletResponse.class), (req, res) -> WeblogPageCache.getInstance().remove(key)); } } From a2804b26da9bdd70e12fbe61039e1ad316d13e74 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Tue, 17 Nov 2026 19:49:22 -0700 Subject: [PATCH 03/10] Keep each request's site URL fixed while it renders, and save the URL only once A request now reads site.absoluteurl once, the first time it builds a link or a cache key, so its links and the key its content is cached under always agree even if an administrator sets the URL meanwhile. Content rendered outside a request isn't cached while the URL is unset, the cache warmup job skips its work until then, and the rendering caches are cleared when the URL is first saved. Saving the URL from setup or an administrator's request now uses compareAndSetProperty(), so when several requests try at once only the first one's URL is kept. Planet links also go through getAbsoluteContextURL() instead of reading the property directly. --- .../business/MultiPlanetURLStrategy.java | 2 +- .../config/WebloggerRuntimeConfig.java | 127 ++++++++++--- .../planet/business/PlanetURLStrategy.java | 2 +- .../ui/rendering/util/cache/PlanetCache.java | 6 +- .../rendering/util/cache/SiteWideCache.java | 6 +- .../util/cache/WeblogCacheWarmupJob.java | 8 + .../rendering/util/cache/WeblogFeedCache.java | 6 +- .../rendering/util/cache/WeblogPageCache.java | 6 +- .../weblogger/business/PropertiesTest.java | 54 ++++++ .../weblogger/config/SiteUrlForAdminTest.java | 31 ++++ .../config/SiteUrlWhileUnsetTest.java | 171 ++++++++++++++++++ 11 files changed, 379 insertions(+), 40 deletions(-) create mode 100644 app/src/test/java/org/apache/roller/weblogger/config/SiteUrlWhileUnsetTest.java diff --git a/app/src/main/java/org/apache/roller/planet/business/MultiPlanetURLStrategy.java b/app/src/main/java/org/apache/roller/planet/business/MultiPlanetURLStrategy.java index 475dbf056..335699645 100644 --- a/app/src/main/java/org/apache/roller/planet/business/MultiPlanetURLStrategy.java +++ b/app/src/main/java/org/apache/roller/planet/business/MultiPlanetURLStrategy.java @@ -42,7 +42,7 @@ public String getPlanetURL(String planet) { } StringBuilder url = new StringBuilder(); - url.append(WebloggerRuntimeConfig.getProperty("site.absoluteurl")); + url.append(WebloggerRuntimeConfig.getAbsoluteContextURL()); url.append('/').append(planet).append('/'); return url.toString(); diff --git a/app/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java b/app/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java index 1ff5cf03d..ba1f90114 100644 --- a/app/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java +++ b/app/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java @@ -33,6 +33,10 @@ import org.apache.roller.weblogger.business.WebloggerFactory; import org.apache.roller.weblogger.pojos.RuntimeConfigProperty; import org.apache.roller.weblogger.pojos.User; +import org.apache.roller.weblogger.ui.rendering.util.cache.PlanetCache; +import org.apache.roller.weblogger.ui.rendering.util.cache.SiteWideCache; +import org.apache.roller.weblogger.ui.rendering.util.cache.WeblogFeedCache; +import org.apache.roller.weblogger.ui.rendering.util.cache.WeblogPageCache; /** @@ -55,7 +59,7 @@ public final class WebloggerRuntimeConfig { // absolute url derived from the request being handled on this thread, used // only while site.absoluteurl is unset and never kept past that request - private static final ThreadLocal requestAbsoluteContextURL = + private static final ThreadLocal requestURLs = new ThreadLocal<>(); private static final AtomicBoolean absoluteURLWarningLogged = new AtomicBoolean(false); @@ -177,6 +181,24 @@ public static String getRuntimeConfigDefsAsString() { } + /** + * The urls seen by the request being handled on this thread. The value of + * site.absoluteurl is read once per request, the first time it's needed, + * so that all links built for a request and the cache key its content is + * stored under agree, even if an administrator sets the property while + * the request is being handled. + */ + private static final class RequestURLs { + private final String requestURL; + private String siteURL; + private boolean siteURLRead; + + private RequestURLs(String requestURL) { + this.requestURL = requestURL; + } + } + + /** * Set the absolute url of the request being handled on this thread. The * InitFilter sets this at the start of each request and clears it with @@ -185,36 +207,68 @@ public static String getRuntimeConfigDefsAsString() { * This value is *not* persisted or shared with other threads. */ public static void setRequestAbsoluteContextURL(String url) { - requestAbsoluteContextURL.set(url); + requestURLs.set(new RequestURLs(url)); } /** - * Forget the absolute url of the request handled on this thread. + * Forget the urls of the request handled on this thread. */ public static void clearRequestAbsoluteContextURL() { - requestAbsoluteContextURL.remove(); + requestURLs.remove(); + } + + + /** + * The value of site.absoluteurl, or null if it is unset. Within a + * request this is the value the property had when the request first + * needed it. + */ + private static String configuredAbsoluteContextURL() { + RequestURLs request = requestURLs.get(); + if (request == null) { + return liveAbsoluteContextURL(); + } + if (!request.siteURLRead) { + request.siteURL = liveAbsoluteContextURL(); + request.siteURLRead = true; + } + return request.siteURL; + } + + + private static String liveAbsoluteContextURL() { + String absURL = getProperty("site.absoluteurl"); + return absURL == null || absURL.isBlank() ? null : absURL; } /** - * True if getAbsoluteContextURL() has returned the current request's url - * on this thread. Output built from that url depends on the request's Host - * header, so the rendering caches don't store it. + * True if site.absoluteurl is set, so links can be built without a + * request. Background tasks check this before building links. */ + public static boolean isAbsoluteContextURLSet() { + return configuredAbsoluteContextURL() != null; + } + + /** - * The cache key to use for content rendered for the current request. While - * site.absoluteurl is unset, links are built from the request's own URL, so - * the key includes it: content cached for one host name is only served to - * requests for that host name. + * The cache key to use for content rendered for the current request, or + * null if the content must not be cached. While site.absoluteurl is + * unset, links are built from the request's own URL, so the key includes + * it: content cached for one host name is only served to requests for + * that host name. Content rendered outside a request while the property + * is unset is not cached, because its links are incomplete. */ public static String cacheKey(String key) { - String absURL = getProperty("site.absoluteurl"); - if (absURL != null && !absURL.isBlank()) { + if (key == null || configuredAbsoluteContextURL() != null) { return key; } - String requestURL = requestAbsoluteContextURL.get(); - return requestURL == null ? key : key + "|" + requestURL; + RequestURLs request = requestURLs.get(); + if (request == null || request.requestURL == null) { + return null; + } + return key + "|" + request.requestURL; } /** @@ -223,13 +277,13 @@ public static String cacheKey(String key) { * time an administrator opens the Roller UI after an upgrade. */ public static void saveAbsoluteContextURLForAdmin(User user) { - String absURL = getProperty("site.absoluteurl"); - if ((absURL != null && !absURL.isBlank()) || user == null + if (liveAbsoluteContextURL() != null || user == null || !user.hasGlobalPermission("admin")) { return; } + RequestURLs request = requestURLs.get(); try { - if (saveAbsoluteContextURLIfUnset(requestAbsoluteContextURL.get())) { + if (request != null && saveAbsoluteContextURLIfUnset(request.requestURL)) { WebloggerFactory.getWeblogger().flush(); } } catch (WebloggerException e) { @@ -249,8 +303,8 @@ public static void saveAbsoluteContextURLForAdmin(User user) { public static String getAbsoluteContextURL() { // db prop takes priority if it exists - String absURL = getProperty("site.absoluteurl"); - if(absURL != null && !absURL.isBlank()) { + String absURL = configuredAbsoluteContextURL(); + if (absURL != null) { return absURL; } @@ -261,7 +315,8 @@ public static String getAbsoluteContextURL() { + "Administration > Configuration."); } - return requestAbsoluteContextURL.get(); + RequestURLs request = requestURLs.get(); + return request == null ? null : request.requestURL; } @@ -270,6 +325,11 @@ public static String getAbsoluteContextURL() { * Called when the site is being set up, by the installer and by the * registration of the first administrator. * + * The property is only replaced if it is still empty when it is written, + * so of several requests trying at once, only one saves its url. The + * rendering caches are cleared when the url is saved, since they hold + * content cached per host name while the property was unset. + * * @return true if the url was saved; the caller must flush */ public static boolean saveAbsoluteContextURLIfUnset(String url) @@ -280,20 +340,35 @@ public static boolean saveAbsoluteContextURLIfUnset(String url) } PropertiesManager pmgr = WebloggerFactory.getWeblogger().getPropertiesManager(); RuntimeConfigProperty prop = pmgr.getProperty("site.absoluteurl"); - if (prop != null && prop.getValue() != null && !prop.getValue().isBlank()) { + String current = prop == null ? null : prop.getValue(); + if (current != null && !current.isBlank()) { return false; } if (prop == null) { - prop = new RuntimeConfigProperty("site.absoluteurl", url); - } else { - prop.setValue(url); + // the properties table is filled in at startup, so this only + // happens if that failed; a second insert would fail on flush + pmgr.saveProperty(new RuntimeConfigProperty("site.absoluteurl", url)); + } else if (!pmgr.compareAndSetProperty("site.absoluteurl", current, url)) { + return false; } - pmgr.saveProperty(prop); + clearRenderingCaches(); log.info("Set site.absoluteurl to " + url); return true; } + /** + * Clear the caches of rendered content, whose links may have been built + * from the url of a request. + */ + private static void clearRenderingCaches() { + WeblogPageCache.getInstance().clear(); + WeblogFeedCache.getInstance().clear(); + SiteWideCache.getInstance().clear(); + PlanetCache.getInstance().clear(); + } + + /** * Special method which sets the non-persisted relative url to this site. * diff --git a/app/src/main/java/org/apache/roller/weblogger/planet/business/PlanetURLStrategy.java b/app/src/main/java/org/apache/roller/weblogger/planet/business/PlanetURLStrategy.java index 66d375536..47d355b8a 100644 --- a/app/src/main/java/org/apache/roller/weblogger/planet/business/PlanetURLStrategy.java +++ b/app/src/main/java/org/apache/roller/weblogger/planet/business/PlanetURLStrategy.java @@ -36,7 +36,7 @@ public class PlanetURLStrategy extends MultiPlanetURLStrategy { @Override public String getPlanetURL(String planet) { StringBuilder url = new StringBuilder(); - url.append(WebloggerRuntimeConfig.getProperty("site.absoluteurl")); + url.append(WebloggerRuntimeConfig.getAbsoluteContextURL()); return url.toString(); } diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/PlanetCache.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/PlanetCache.java index 1a17ca19b..b15fd2e68 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/PlanetCache.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/PlanetCache.java @@ -101,7 +101,7 @@ public static PlanetCache getInstance() { public Object get(String key) { key = WebloggerRuntimeConfig.cacheKey(key); - if (!cacheEnabled) { + if (!cacheEnabled || key == null) { return null; } @@ -120,7 +120,7 @@ public Object get(String key) { public void put(String key, Object value) { key = WebloggerRuntimeConfig.cacheKey(key); - if (!cacheEnabled) { + if (!cacheEnabled || key == null) { return; } @@ -132,7 +132,7 @@ public void put(String key, Object value) { public void remove(String key) { key = WebloggerRuntimeConfig.cacheKey(key); - if (!cacheEnabled) { + if (!cacheEnabled || key == null) { return; } diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/SiteWideCache.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/SiteWideCache.java index eebbced19..6e1f5c462 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/SiteWideCache.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/SiteWideCache.java @@ -106,7 +106,7 @@ public static SiteWideCache getInstance() { public Object get(String key) { key = WebloggerRuntimeConfig.cacheKey(key); - if (!cacheEnabled) { + if (!cacheEnabled || key == null) { return null; } @@ -125,7 +125,7 @@ public Object get(String key) { public void put(String key, Object value) { key = WebloggerRuntimeConfig.cacheKey(key); - if (!cacheEnabled) { + if (!cacheEnabled || key == null) { return; } @@ -137,7 +137,7 @@ public void put(String key, Object value) { public void remove(String key) { key = WebloggerRuntimeConfig.cacheKey(key); - if (!cacheEnabled) { + if (!cacheEnabled || key == null) { return; } diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogCacheWarmupJob.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogCacheWarmupJob.java index 347fa071c..1a8e1371b 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogCacheWarmupJob.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogCacheWarmupJob.java @@ -27,6 +27,7 @@ import org.apache.roller.util.RollerConstants; import org.apache.roller.weblogger.business.runnable.Job; import org.apache.roller.weblogger.config.WebloggerConfig; +import org.apache.roller.weblogger.config.WebloggerRuntimeConfig; import org.apache.roller.weblogger.pojos.StaticTemplate; import org.apache.roller.weblogger.pojos.Template; import org.apache.roller.weblogger.pojos.TemplateRendition.TemplateLanguage; @@ -103,6 +104,13 @@ private void warmupFeedCache(List weblogs, String type, String format) { return; } + // without site.absoluteurl, feeds rendered outside a request have no + // absolute links, so there is nothing worth caching yet + if (!WebloggerRuntimeConfig.isAbsoluteContextURLSet()) { + log.info("Skipping cache warmup because site.absoluteurl is not set"); + return; + } + // we are working on the feed cache WeblogFeedCache feedCache = WeblogFeedCache.getInstance(); long start = System.currentTimeMillis(); diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogFeedCache.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogFeedCache.java index ebc7f724a..39eca3639 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogFeedCache.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogFeedCache.java @@ -92,7 +92,7 @@ public static WeblogFeedCache getInstance() { public Object get(String key, long lastModified) { key = WebloggerRuntimeConfig.cacheKey(key); - if (!cacheEnabled) { + if (!cacheEnabled || key == null) { return null; } @@ -120,7 +120,7 @@ public Object get(String key, long lastModified) { public void put(String key, Object value) { key = WebloggerRuntimeConfig.cacheKey(key); - if (!cacheEnabled) { + if (!cacheEnabled || key == null) { return; } @@ -132,7 +132,7 @@ public void put(String key, Object value) { public void remove(String key) { key = WebloggerRuntimeConfig.cacheKey(key); - if (!cacheEnabled) { + if (!cacheEnabled || key == null) { return; } diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogPageCache.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogPageCache.java index 0afddd336..c5bef3f95 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogPageCache.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/cache/WeblogPageCache.java @@ -91,7 +91,7 @@ public static WeblogPageCache getInstance() { public Object get(String key, long lastModified) { key = WebloggerRuntimeConfig.cacheKey(key); - if (!cacheEnabled) { + if (!cacheEnabled || key == null) { return null; } @@ -118,7 +118,7 @@ public Object get(String key, long lastModified) { public void put(String key, Object value) { key = WebloggerRuntimeConfig.cacheKey(key); - if (!cacheEnabled) { + if (!cacheEnabled || key == null) { return; } @@ -130,7 +130,7 @@ public void put(String key, Object value) { public void remove(String key) { key = WebloggerRuntimeConfig.cacheKey(key); - if (!cacheEnabled) { + if (!cacheEnabled || key == null) { return; } diff --git a/app/src/test/java/org/apache/roller/weblogger/business/PropertiesTest.java b/app/src/test/java/org/apache/roller/weblogger/business/PropertiesTest.java index b1ee0ee0d..bf4d987d2 100644 --- a/app/src/test/java/org/apache/roller/weblogger/business/PropertiesTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/business/PropertiesTest.java @@ -22,6 +22,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.roller.weblogger.TestUtils; +import org.apache.roller.weblogger.config.WebloggerRuntimeConfig; import org.apache.roller.weblogger.pojos.RuntimeConfigProperty; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -130,6 +131,59 @@ public void compareAndSetAllowsOnlyOneConcurrentWinner() throws Exception { } } + @Test + public void onlyOneConcurrentRequestSavesTheSiteUrl() throws Exception { + PropertiesManager mgr = WebloggerFactory.getWeblogger().getPropertiesManager(); + RuntimeConfigProperty prop = mgr.getProperty("site.absoluteurl"); + String original = prop.getValue(); + prop.setValue(""); + mgr.saveProperty(prop); + TestUtils.endSession(true); + + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = executor.submit(() -> saveSiteUrlAfterSignal( + "https://first.example.org", ready, start)); + Future second = executor.submit(() -> saveSiteUrlAfterSignal( + "https://second.example.org", ready, start)); + ready.await(); + start.countDown(); + + boolean firstSaved = first.get(); + boolean secondSaved = second.get(); + assertNotEquals(firstSaved, secondSaved, "exactly one request must save the URL"); + + RuntimeConfigProperty saved = WebloggerFactory.getWeblogger() + .getPropertiesManager().getProperty("site.absoluteurl"); + assertEquals(firstSaved ? "https://first.example.org" : "https://second.example.org", + saved.getValue()); + saved.setValue(original); + WebloggerFactory.getWeblogger().getPropertiesManager().saveProperty(saved); + TestUtils.endSession(true); + } finally { + executor.shutdownNow(); + } + } + + private boolean saveSiteUrlAfterSignal(String url, CountDownLatch ready, + CountDownLatch start) throws Exception { + try { + // both requests find the property empty before either saves it + String current = WebloggerFactory.getWeblogger().getPropertiesManager() + .getProperty("site.absoluteurl").getValue(); + assertTrue(current == null || current.isEmpty()); + ready.countDown(); + start.await(); + boolean saved = WebloggerRuntimeConfig.saveAbsoluteContextURLIfUnset(url); + WebloggerFactory.getWeblogger().flush(); + return saved; + } finally { + WebloggerFactory.getWeblogger().release(); + } + } + private boolean compareAndSetAfterSignal(String name, String value, CountDownLatch ready, CountDownLatch start) throws Exception { ready.countDown(); diff --git a/app/src/test/java/org/apache/roller/weblogger/config/SiteUrlForAdminTest.java b/app/src/test/java/org/apache/roller/weblogger/config/SiteUrlForAdminTest.java index 6bb6845fa..481d4027e 100644 --- a/app/src/test/java/org/apache/roller/weblogger/config/SiteUrlForAdminTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/config/SiteUrlForAdminTest.java @@ -32,7 +32,10 @@ import org.mockito.MockedStatic; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; @@ -101,4 +104,32 @@ void aConfiguredSiteUrlIsKept() throws Exception { verify(properties, never()).saveProperty(any()); } + + @Test + void anEmptySiteUrlIsOnlySavedIfStillEmpty() throws Exception { + when(properties.getProperty("site.absoluteurl")).thenReturn( + new RuntimeConfigProperty("site.absoluteurl", "")); + when(properties.compareAndSetProperty("site.absoluteurl", "", + "https://blog.example.org/roller")).thenReturn(true); + + assertTrue(WebloggerRuntimeConfig.saveAbsoluteContextURLIfUnset( + "https://blog.example.org/roller")); + verify(properties).compareAndSetProperty("site.absoluteurl", "", + "https://blog.example.org/roller"); + verify(properties, never()).saveProperty(any()); + } + + @Test + void aSiteUrlSavedByAnotherRequestIsKept() throws Exception { + // this request read the property while it was empty, but another + // request saved a URL before this one could + when(properties.getProperty("site.absoluteurl")).thenReturn( + new RuntimeConfigProperty("site.absoluteurl", "")); + when(properties.compareAndSetProperty(eq("site.absoluteurl"), eq(""), any())) + .thenReturn(false); + + assertFalse(WebloggerRuntimeConfig.saveAbsoluteContextURLIfUnset( + "https://blog.example.org/roller")); + verify(properties, never()).saveProperty(any()); + } } diff --git a/app/src/test/java/org/apache/roller/weblogger/config/SiteUrlWhileUnsetTest.java b/app/src/test/java/org/apache/roller/weblogger/config/SiteUrlWhileUnsetTest.java new file mode 100644 index 000000000..8fc303113 --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/config/SiteUrlWhileUnsetTest.java @@ -0,0 +1,171 @@ +/* + * 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.config; + +import org.apache.roller.planet.business.MultiPlanetURLStrategy; +import org.apache.roller.weblogger.business.PropertiesManager; +import org.apache.roller.weblogger.business.Weblogger; +import org.apache.roller.weblogger.business.WebloggerFactory; +import org.apache.roller.weblogger.planet.business.PlanetURLStrategy; +import org.apache.roller.weblogger.pojos.RuntimeConfigProperty; +import org.apache.roller.weblogger.ui.rendering.util.cache.PlanetCache; +import org.apache.roller.weblogger.ui.rendering.util.cache.SiteWideCache; +import org.apache.roller.weblogger.ui.rendering.util.cache.WeblogFeedCache; +import org.apache.roller.weblogger.ui.rendering.util.cache.WeblogPageCache; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + +/** + * Links and cached content while site.absoluteurl is unset, and when it is + * set while content is being rendered. + */ +class SiteUrlWhileUnsetTest { + + private static final String SITE_URL = "https://blog.example.org/roller"; + + private MockedStatic factory; + private PropertiesManager properties; + private String key; + + @BeforeEach + void setUp() throws Exception { + properties = mock(PropertiesManager.class); + // a fresh copy on each read, as a new persistence session would load + when(properties.getProperty("site.absoluteurl")).thenAnswer( + invocation -> new RuntimeConfigProperty("site.absoluteurl", "")); + Weblogger weblogger = mock(Weblogger.class); + when(weblogger.getPropertiesManager()).thenReturn(properties); + factory = mockStatic(WebloggerFactory.class); + factory.when(WebloggerFactory::getWeblogger).thenReturn(weblogger); + key = "SiteUrlWhileUnsetTest/" + System.nanoTime(); + } + + @AfterEach + void tearDown() { + WebloggerRuntimeConfig.clearRequestAbsoluteContextURL(); + WeblogPageCache.getInstance().clear(); + WeblogFeedCache.getInstance().clear(); + SiteWideCache.getInstance().clear(); + PlanetCache.getInstance().clear(); + factory.close(); + } + + private void siteUrlIsSet() throws Exception { + when(properties.getProperty("site.absoluteurl")).thenAnswer( + invocation -> new RuntimeConfigProperty("site.absoluteurl", SITE_URL)); + } + + private static void putEverywhere(String key, Object value) { + WeblogPageCache.getInstance().put(key, value); + WeblogFeedCache.getInstance().put(key, value); + SiteWideCache.getInstance().put(key, value); + PlanetCache.getInstance().put(key, value); + } + + private static void assertNothingCached(String key) { + assertNull(WeblogPageCache.getInstance().get(key, 0)); + assertNull(WeblogFeedCache.getInstance().get(key, 0)); + assertNull(SiteWideCache.getInstance().get(key)); + assertNull(PlanetCache.getInstance().get(key)); + } + + @Test + void aRenderThatStartedWithoutTheSiteUrlIsNotServedToOtherHosts() throws Exception { + // a request starts while the URL is unset and builds its links from + // its own host name + WebloggerRuntimeConfig.setRequestAbsoluteContextURL("http://other.example.com"); + assertEquals("http://other.example.com", WebloggerRuntimeConfig.getAbsoluteContextURL()); + + // an administrator saves the site URL before that request is cached + siteUrlIsSet(); + assertEquals("http://other.example.com", WebloggerRuntimeConfig.getAbsoluteContextURL(), + "links in one rendering must all use the same URL"); + putEverywhere(key, "rendered for other.example.com"); + WebloggerRuntimeConfig.clearRequestAbsoluteContextURL(); + + // a later request uses the shared cache key + WebloggerRuntimeConfig.setRequestAbsoluteContextURL("https://blog.example.org/roller"); + assertEquals(SITE_URL, WebloggerRuntimeConfig.getAbsoluteContextURL()); + assertNothingCached(key); + } + + @Test + void backgroundRenderingIsNotCachedWhileTheSiteUrlIsUnset() throws Exception { + // the cache warmup job renders feeds outside of any request + WeblogFeedCache.getInstance().put(key, "warmed without a site URL"); + PlanetCache.getInstance().put(key, "warmed without a site URL"); + + siteUrlIsSet(); + WebloggerRuntimeConfig.setRequestAbsoluteContextURL(SITE_URL); + assertNull(WeblogFeedCache.getInstance().get(key, 0)); + assertNull(PlanetCache.getInstance().get(key)); + } + + @Test + void backgroundRenderingIsCachedOnceTheSiteUrlIsSet() throws Exception { + siteUrlIsSet(); + WeblogFeedCache.getInstance().put(key, "warmed"); + + WebloggerRuntimeConfig.setRequestAbsoluteContextURL("http://other.example.com"); + assertEquals("warmed", WeblogFeedCache.getInstance().get(key, 0)); + } + + @Test + void savingTheSiteUrlClearsContentCachedPerHost() throws Exception { + WebloggerRuntimeConfig.setRequestAbsoluteContextURL("http://other.example.com"); + putEverywhere(key, "rendered for other.example.com"); + when(properties.compareAndSetProperty(eq("site.absoluteurl"), eq(""), any())) + .thenReturn(true); + + assertTrue(WebloggerRuntimeConfig.saveAbsoluteContextURLIfUnset(SITE_URL)); + + assertNothingCached(key); + } + + @Test + void planetLinksUseTheRequestUrlWhileTheSiteUrlIsUnset() { + WebloggerRuntimeConfig.setRequestAbsoluteContextURL("http://other.example.com"); + + assertEquals("http://other.example.com/ignored/", + new MultiPlanetURLStrategy().getPlanetURL("ignored")); + assertEquals("http://other.example.com/ignored/group/all/feed/rss", + new MultiPlanetURLStrategy().getPlanetGroupFeedURL("ignored", "all", "rss")); + assertEquals("http://other.example.com", + new PlanetURLStrategy().getPlanetURL("ignored")); + } + + @Test + void planetLinksUseTheSiteUrlOnceSet() throws Exception { + siteUrlIsSet(); + WebloggerRuntimeConfig.setRequestAbsoluteContextURL("http://other.example.com"); + + assertEquals(SITE_URL + "/ignored/", new MultiPlanetURLStrategy().getPlanetURL("ignored")); + assertEquals(SITE_URL, new PlanetURLStrategy().getPlanetURL("ignored")); + } +} From 9fb2bb5123e4940634d5121a79c442f5feb7cfb9 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Tue, 17 Nov 2026 19:56:45 -0700 Subject: [PATCH 04/10] Build links in emails only from the configured site URL While site.absoluteurl is unset, comment and approval notifications are still sent but leave out their links, since the only URL available is the host name of the request that caused them. Activation, invitation and pending entry emails exist to deliver a link, so they aren't sent: activation and invitation report why to the caller, and the pending entry notice logs a warning. --- .../roller/weblogger/util/MailUtil.java | 99 ++++++-- .../weblogger/util/MailUtilSiteUrlTest.java | 240 ++++++++++++++++++ 2 files changed, 312 insertions(+), 27 deletions(-) create mode 100644 app/src/test/java/org/apache/roller/weblogger/util/MailUtilSiteUrlTest.java diff --git a/app/src/main/java/org/apache/roller/weblogger/util/MailUtil.java b/app/src/main/java/org/apache/roller/weblogger/util/MailUtil.java index 54038af53..cda484785 100644 --- a/app/src/main/java/org/apache/roller/weblogger/util/MailUtil.java +++ b/app/src/main/java/org/apache/roller/weblogger/util/MailUtil.java @@ -72,6 +72,16 @@ public static boolean isMailConfigured() { return WebloggerStartup.getMailProvider() != null; } + /** + * True if site.absoluteurl is set. Links in emails are only built from + * that setting, never from the request that caused the email, because + * the request's host name is chosen by whoever sent it. + */ + private static boolean canLinkToSite() { + return WebloggerRuntimeConfig.isAbsoluteContextURLSet(); + } + + /** * Send an email notice that a new pending entry has been submitted. */ @@ -83,6 +93,13 @@ public static void sendPendingEntryNotice(WeblogEntry entry) throws WebloggerExc if (mailSession == null) { throw new WebloggerException("Couldn't get mail Session"); } + + if (!canLinkToSite()) { + log.warn("No email was sent about the pending entry \"" + entry.getTitle() + + "\" because the site's absolute URL is not set. Set it under " + + "Server Administration > Configuration."); + return; + } try { WeblogManager wmgr = WebloggerFactory.getWeblogger().getWeblogManager(); @@ -152,6 +169,13 @@ public static void sendWeblogInvitation(Weblog website, User user) throw new WebloggerException("ERROR: Notification email(s) not sent, " + "Roller's mail session not properly configured"); } + + if (!canLinkToSite()) { + throw new WebloggerException("The invitation was saved, but no email " + + "was sent because the site's absolute URL is not set. An " + + "administrator can set it under Server Administration > " + + "Configuration."); + } try { String from = website.getEmailAddress(); @@ -208,6 +232,12 @@ public static void sendUserActivationEmail(User user) throw new WebloggerException("ERROR: Notification email(s) not sent, " + "Roller's mail session not properly configured"); } + + if (!canLinkToSite()) { + throw new WebloggerException("No activation email was sent because " + + "the site's absolute URL is not set. Set it under Server " + + "Administration > Configuration."); + } try { ResourceBundle resources = ResourceBundle.getBundle( @@ -335,19 +365,27 @@ public static void sendEmailNotification(WeblogEntryComment commentObject, msg.append((isPlainText) ? commentObject.getContent() : Utilities.transformToHTMLSubset(Utilities.escapeHTML(commentObject.getContent()))); - msg.append((isPlainText) ? "\n\n----\n" - : "


"); - msg.append(resources.getString("email.comment.respond") + ": "); - msg.append((isPlainText) ? "\n" : "
"); - - // Build link back to comment - String commentURL = WebloggerFactory.getWeblogger() - .getUrlStrategy().getWeblogCommentsURL(weblog, null, entry.getAnchor(), true); - - if (isPlainText) { - msg.append(commentURL); - } else { - msg.append(""+commentURL+"
"); + // links are left out while the site's absolute URL is unset + boolean linkToSite = canLinkToSite(); + if (!linkToSite) { + log.debug("Leaving links out of comment email because site.absoluteurl is not set"); + } + + if (linkToSite) { + msg.append((isPlainText) ? "\n\n----\n" + : "


"); + msg.append(resources.getString("email.comment.respond") + ": "); + msg.append((isPlainText) ? "\n" : "
"); + + // Build link back to comment + String commentURL = WebloggerFactory.getWeblogger() + .getUrlStrategy().getWeblogCommentsURL(weblog, null, entry.getAnchor(), true); + + if (isPlainText) { + msg.append(commentURL); + } else { + msg.append(""+commentURL+"
"); + } } // next the additional information that is sent to the blog owner @@ -400,19 +438,24 @@ public static void sendEmailNotification(WeblogEntryComment commentObject, ownermsg.append((isPlainText) ? "\n\n" : "

"); } // add link to weblog edit page so user can login to manage comments - ownermsg.append(resources.getString("email.comment.management.link") + ": "); - ownermsg.append((isPlainText) ? "\n" : "
"); + if (linkToSite) { + ownermsg.append(resources.getString("email.comment.management.link") + ": "); + ownermsg.append((isPlainText) ? "\n" : "
"); - Map parameters = new HashMap<>(); - parameters.put("bean.entryId", entry.getId()); - String deleteURL = WebloggerFactory.getWeblogger().getUrlStrategy().getActionURL( - "comments", "/roller-ui/authoring", weblog.getHandle(), parameters, true); + Map parameters = new HashMap<>(); + parameters.put("bean.entryId", entry.getId()); + String deleteURL = WebloggerFactory.getWeblogger().getUrlStrategy().getActionURL( + "comments", "/roller-ui/authoring", weblog.getHandle(), parameters, true); - if (isPlainText) { - ownermsg.append(deleteURL); - } else { - ownermsg.append( - "" + deleteURL + ""); + if (isPlainText) { + ownermsg.append(deleteURL); + } else { + ownermsg.append("" + deleteURL + ""); + } + } + + if (!isPlainText) { + ownermsg.append(""); msg.append(""); ownermsg.append(""); } @@ -534,9 +577,11 @@ public static void sendEmailApprovalNotification(WeblogEntryComment cd, I18nMess StringBuilder msg = new StringBuilder(); msg.append(resources.getString("email.comment.commentApproved")); - msg.append("\n\n"); - msg.append(WebloggerFactory.getWeblogger().getUrlStrategy() - .getWeblogCommentsURL(weblog, null, entry.getAnchor(), true)); + if (canLinkToSite()) { + msg.append("\n\n"); + msg.append(WebloggerFactory.getWeblogger().getUrlStrategy() + .getWeblogCommentsURL(weblog, null, entry.getAnchor(), true)); + } // send message to author of approved comment try { diff --git a/app/src/test/java/org/apache/roller/weblogger/util/MailUtilSiteUrlTest.java b/app/src/test/java/org/apache/roller/weblogger/util/MailUtilSiteUrlTest.java new file mode 100644 index 000000000..59a547277 --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/util/MailUtilSiteUrlTest.java @@ -0,0 +1,240 @@ +/* + * 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.util; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Properties; + +import jakarta.mail.Address; +import jakarta.mail.Message; +import jakarta.mail.Session; +import jakarta.mail.Transport; + +import org.apache.roller.weblogger.WebloggerException; +import org.apache.roller.weblogger.business.MailProvider; +import org.apache.roller.weblogger.business.PropertiesManager; +import org.apache.roller.weblogger.business.URLStrategy; +import org.apache.roller.weblogger.business.WeblogManager; +import org.apache.roller.weblogger.business.Weblogger; +import org.apache.roller.weblogger.business.WebloggerFactory; +import org.apache.roller.weblogger.business.startup.WebloggerStartup; +import org.apache.roller.weblogger.config.WebloggerRuntimeConfig; +import org.apache.roller.weblogger.pojos.RuntimeConfigProperty; +import org.apache.roller.weblogger.pojos.User; +import org.apache.roller.weblogger.pojos.Weblog; +import org.apache.roller.weblogger.pojos.WeblogEntry; +import org.apache.roller.weblogger.pojos.WeblogEntryComment; +import org.apache.roller.weblogger.pojos.WeblogPermission; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; + +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; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + +/** + * Emails only link to the site through site.absoluteurl, never through the + * host name of the request that caused them. + */ +class MailUtilSiteUrlTest { + + private static final String REQUEST_URL = "http://forged.example.net"; + private static final String SITE_URL = "https://blog.example.org"; + + private MockedStatic factory; + private MockedStatic startup; + private PropertiesManager properties; + private WeblogManager weblogs; + private final List sent = new ArrayList<>(); + + @BeforeEach + void setUp() throws Exception { + properties = mock(PropertiesManager.class); + siteUrl(""); + when(properties.getProperty("users.comments.emailnotify")).thenAnswer( + invocation -> new RuntimeConfigProperty("users.comments.emailnotify", "true")); + + URLStrategy urls = mock(URLStrategy.class); + when(urls.getWeblogCommentsURL(any(), isNull(), anyString(), anyBoolean())).thenAnswer( + invocation -> WebloggerRuntimeConfig.getAbsoluteContextURL() + "/blog/entry/first#comments"); + when(urls.getActionURL(eq("comments"), anyString(), anyString(), any(), anyBoolean())).thenAnswer( + invocation -> WebloggerRuntimeConfig.getAbsoluteContextURL() + "/roller-ui/authoring/comments.rol"); + when(urls.getEntryEditURL(anyString(), anyString(), anyBoolean())).thenAnswer( + invocation -> WebloggerRuntimeConfig.getAbsoluteContextURL() + "/roller-ui/authoring/entryEdit.rol"); + + weblogs = mock(WeblogManager.class); + Weblogger weblogger = mock(Weblogger.class); + when(weblogger.getPropertiesManager()).thenReturn(properties); + when(weblogger.getUrlStrategy()).thenReturn(urls); + when(weblogger.getWeblogManager()).thenReturn(weblogs); + factory = mockStatic(WebloggerFactory.class); + factory.when(WebloggerFactory::getWeblogger).thenReturn(weblogger); + + Transport transport = mock(Transport.class); + doAnswer(invocation -> { + sent.add(String.valueOf(((Message) invocation.getArgument(0)).getContent())); + return null; + }).when(transport).sendMessage(any(Message.class), any(Address[].class)); + MailProvider mail = mock(MailProvider.class); + when(mail.getSession()).thenReturn(Session.getInstance(new Properties())); + when(mail.getTransport()).thenReturn(transport); + startup = mockStatic(WebloggerStartup.class); + startup.when(WebloggerStartup::getMailProvider).thenReturn(mail); + + WebloggerRuntimeConfig.setRequestAbsoluteContextURL(REQUEST_URL); + } + + @AfterEach + void tearDown() { + WebloggerRuntimeConfig.clearRequestAbsoluteContextURL(); + startup.close(); + factory.close(); + } + + private void siteUrl(String url) throws Exception { + when(properties.getProperty("site.absoluteurl")).thenAnswer( + invocation -> new RuntimeConfigProperty("site.absoluteurl", url)); + } + + private static User user() { + User user = mock(User.class); + when(user.getUserName()).thenReturn("owner"); + when(user.getFullName()).thenReturn("Blog Owner"); + when(user.getEmailAddress()).thenReturn("owner@example.org"); + when(user.getLocale()).thenReturn("en"); + when(user.getActivationCode()).thenReturn("code"); + return user; + } + + private static Weblog weblog() { + Weblog weblog = mock(Weblog.class); + when(weblog.getHandle()).thenReturn("blog"); + when(weblog.getName()).thenReturn("Blog"); + when(weblog.getEmailAddress()).thenReturn("blog@example.org"); + when(weblog.getLocaleInstance()).thenReturn(Locale.ENGLISH); + when(weblog.getEmailComments()).thenReturn(true); + return weblog; + } + + private static WeblogEntryComment pendingComment() { + Weblog weblog = weblog(); + User owner = user(); + WeblogEntry entry = mock(WeblogEntry.class); + when(entry.getWebsite()).thenReturn(weblog); + when(entry.getCreator()).thenReturn(owner); + when(entry.getAnchor()).thenReturn("first"); + when(entry.getTitle()).thenReturn("First"); + when(entry.getId()).thenReturn("entry-id"); + WeblogEntryComment comment = mock(WeblogEntryComment.class); + when(comment.getWeblogEntry()).thenReturn(entry); + when(comment.getPending()).thenReturn(true); + when(comment.getApproved()).thenReturn(false); + when(comment.getName()).thenReturn("Visitor"); + when(comment.getEmail()).thenReturn("visitor@example.org"); + when(comment.getContent()).thenReturn("Nice post"); + return comment; + } + + private static void sendCommentNotification() throws Exception { + MailUtil.sendEmailNotification(pendingComment(), new RollerMessages(), + I18nMessages.getMessages(Locale.ENGLISH), true); + } + + @Test + void commentNotificationsLeaveOutLinksWhileTheSiteUrlIsUnset() throws Exception { + sendCommentNotification(); + + assertEquals(1, sent.size(), "the owner is still told about the comment"); + assertTrue(sent.get(0).contains("Nice post")); + assertFalse(sent.get(0).contains("forged.example.net"), sent.get(0)); + } + + @Test + void commentNotificationsLinkToTheSiteUrlOnceSet() throws Exception { + siteUrl(SITE_URL); + + sendCommentNotification(); + + assertEquals(1, sent.size()); + assertTrue(sent.get(0).contains(SITE_URL + "/blog/entry/first#comments"), sent.get(0)); + assertTrue(sent.get(0).contains(SITE_URL + "/roller-ui/authoring/comments.rol"), sent.get(0)); + assertFalse(sent.get(0).contains("forged.example.net")); + } + + @Test + void approvalNotificationsLeaveOutLinksWhileTheSiteUrlIsUnset() throws Exception { + MailUtil.sendEmailApprovalNotification(pendingComment(), + I18nMessages.getMessages(Locale.ENGLISH)); + + assertEquals(1, sent.size()); + assertFalse(sent.get(0).contains("forged.example.net"), sent.get(0)); + } + + @Test + void invitationsAreNotEmailedWhileTheSiteUrlIsUnset() { + assertThrows(WebloggerException.class, + () -> MailUtil.sendWeblogInvitation(weblog(), user())); + assertTrue(sent.isEmpty(), String.valueOf(sent)); + } + + @Test + void activationsAreNotEmailedWhileTheSiteUrlIsUnset() { + assertThrows(WebloggerException.class, () -> MailUtil.sendUserActivationEmail(user())); + assertTrue(sent.isEmpty(), String.valueOf(sent)); + } + + @Test + void activationsLinkToTheSiteUrlOnceSet() throws Exception { + siteUrl(SITE_URL); + + MailUtil.sendUserActivationEmail(user()); + + assertEquals(1, sent.size()); + assertTrue(sent.get(0).contains(SITE_URL + "/roller-ui/register!activate.rol"), sent.get(0)); + } + + @Test + void pendingEntryNoticesAreNotEmailedWhileTheSiteUrlIsUnset() throws Exception { + Weblog weblog = weblog(); + User author = user(); + when(weblog.hasUserPermission(any(User.class), eq(WeblogPermission.POST))).thenReturn(true); + when(weblogs.getWeblogUsers(weblog, true)).thenReturn(List.of(author)); + WeblogEntry entry = mock(WeblogEntry.class); + when(entry.getWebsite()).thenReturn(weblog); + when(entry.getCreator()).thenReturn(author); + when(entry.getId()).thenReturn("entry-id"); + + MailUtil.sendPendingEntryNotice(entry); + + assertTrue(sent.isEmpty(), String.valueOf(sent)); + } +} From 5d5b154e96d3a55d29da7859778afb0deb159cc5 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Tue, 17 Nov 2026 19:56:45 -0700 Subject: [PATCH 05/10] Wait for the site URL before syncing local weblogs into the planet The planet sync task and the local feed fetcher store absolute links to each weblog. Until site.absoluteurl is set they can't build those links, so they skip their work instead of storing incomplete URLs. --- .../business/WebloggerRomeFeedFetcher.java | 7 ++ .../planet/tasks/SyncWebsitesTask.java | 10 +++ .../planet/business/PlanetSiteUrlTest.java | 80 +++++++++++++++++++ 3 files changed, 97 insertions(+) create mode 100644 app/src/test/java/org/apache/roller/weblogger/planet/business/PlanetSiteUrlTest.java diff --git a/app/src/main/java/org/apache/roller/weblogger/planet/business/WebloggerRomeFeedFetcher.java b/app/src/main/java/org/apache/roller/weblogger/planet/business/WebloggerRomeFeedFetcher.java index 876c46079..361c81ecd 100644 --- a/app/src/main/java/org/apache/roller/weblogger/planet/business/WebloggerRomeFeedFetcher.java +++ b/app/src/main/java/org/apache/roller/weblogger/planet/business/WebloggerRomeFeedFetcher.java @@ -75,6 +75,13 @@ public Subscription fetchSubscription(String feedURL, Date lastModified) return super.fetchSubscription(feedURL, lastModified); } + // the subscription and its entries store absolute links to the + // weblog, which can't be built until site.absoluteurl is set + if (!WebloggerRuntimeConfig.isAbsoluteContextURLSet()) { + log.debug("Skipping LOCAL feed until site.absoluteurl is set - " + feedURL); + return null; + } + // extract blog handle from our special feed url String weblogHandle = null; String[] items = feedURL.split(":", 2); diff --git a/app/src/main/java/org/apache/roller/weblogger/planet/tasks/SyncWebsitesTask.java b/app/src/main/java/org/apache/roller/weblogger/planet/tasks/SyncWebsitesTask.java index 37320bb73..ec1428017 100644 --- a/app/src/main/java/org/apache/roller/weblogger/planet/tasks/SyncWebsitesTask.java +++ b/app/src/main/java/org/apache/roller/weblogger/planet/tasks/SyncWebsitesTask.java @@ -40,6 +40,7 @@ import org.apache.roller.weblogger.business.runnable.RollerTaskWithLeasing; import org.apache.roller.weblogger.business.startup.WebloggerStartup; import org.apache.roller.weblogger.config.WebloggerConfig; +import org.apache.roller.weblogger.config.WebloggerRuntimeConfig; import org.apache.roller.weblogger.pojos.Weblog; @@ -147,6 +148,15 @@ public void runTask() { return; } + // subscriptions store each weblog's absolute URL, which can't be + // built until site.absoluteurl is set + if (!WebloggerRuntimeConfig.isAbsoluteContextURLSet()) { + log.warn("Not syncing local weblogs with planet subscriptions because " + + "the site's absolute URL is not set. Set it under Server " + + "Administration > Configuration."); + return; + } + log.info("Syncing local weblogs with planet subscriptions list"); try { diff --git a/app/src/test/java/org/apache/roller/weblogger/planet/business/PlanetSiteUrlTest.java b/app/src/test/java/org/apache/roller/weblogger/planet/business/PlanetSiteUrlTest.java new file mode 100644 index 000000000..d3ee403d9 --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/planet/business/PlanetSiteUrlTest.java @@ -0,0 +1,80 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.roller.weblogger.planet.business; + +import org.apache.roller.weblogger.business.PropertiesManager; +import org.apache.roller.weblogger.business.Weblogger; +import org.apache.roller.weblogger.business.WebloggerFactory; +import org.apache.roller.weblogger.config.WebloggerConfig; +import org.apache.roller.weblogger.planet.tasks.SyncWebsitesTask; +import org.apache.roller.weblogger.pojos.RuntimeConfigProperty; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; + +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Planet tasks don't store links to local weblogs while site.absoluteurl is + * unset, since they have no request to take a host name from. + */ +class PlanetSiteUrlTest { + + private MockedStatic factory; + private Weblogger weblogger; + + @BeforeEach + void setUp() throws Exception { + PropertiesManager properties = mock(PropertiesManager.class); + when(properties.getProperty("site.absoluteurl")).thenAnswer( + invocation -> new RuntimeConfigProperty("site.absoluteurl", "")); + weblogger = mock(Weblogger.class); + when(weblogger.getPropertiesManager()).thenReturn(properties); + factory = mockStatic(WebloggerFactory.class); + factory.when(WebloggerFactory::getWeblogger).thenReturn(weblogger); + } + + @AfterEach + void tearDown() { + factory.close(); + } + + @Test + void localFeedsAreNotFetchedWhileTheSiteUrlIsUnset() throws Exception { + assertNull(new WebloggerRomeFeedFetcher().fetchSubscription("weblogger:blog", null)); + verify(weblogger, never()).getWeblogManager(); + } + + @Test + void weblogsAreNotSyncedWhileTheSiteUrlIsUnset() { + try (MockedStatic config = mockStatic(WebloggerConfig.class)) { + config.when(() -> WebloggerConfig.getBooleanProperty("planet.aggregator.enabled")) + .thenReturn(true); + + new SyncWebsitesTask().runTask(); + } + verify(weblogger, never()).getPlanetManager(); + verify(weblogger, never()).getWeblogManager(); + } +} From a4d494fa6e5e1b8b5b989eecb2f1f6d8c02e9696 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Tue, 17 Nov 2026 19:56:45 -0700 Subject: [PATCH 06/10] Don't save a local or internal address as the site URL The installer, the first administrator's registration and the first administrator request only save their URL as site.absoluteurl when its host looks like a public name. Loopback and private addresses, and host names without a dot such as localhost or a proxy's backend name, are left for an administrator to set under Server Administration > Configuration. --- .../config/WebloggerRuntimeConfig.java | 55 +++++++++++++++++++ .../weblogger/config/SiteUrlForAdminTest.java | 20 +++++++ 2 files changed, 75 insertions(+) diff --git a/app/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java b/app/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java index ba1f90114..5ec8b9ad4 100644 --- a/app/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java +++ b/app/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java @@ -22,9 +22,16 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; +import java.net.Inet6Address; +import java.net.InetAddress; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.UnknownHostException; +import java.util.Locale; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.apache.commons.validator.routines.InetAddressValidator; import org.apache.roller.util.RollerConstants; import org.apache.roller.weblogger.config.runtime.RuntimeConfigDefs; import org.apache.roller.weblogger.config.runtime.RuntimeConfigDefsParser; @@ -63,6 +70,8 @@ public final class WebloggerRuntimeConfig { new ThreadLocal<>(); private static final AtomicBoolean absoluteURLWarningLogged = new AtomicBoolean(false); + private static final AtomicBoolean localURLWarningLogged = + new AtomicBoolean(false); // prevent instantiations @@ -338,6 +347,15 @@ public static boolean saveAbsoluteContextURLIfUnset(String url) if (url == null || url.isBlank()) { return false; } + if (!isPublicSiteURL(url)) { + if (localURLWarningLogged.compareAndSet(false, true)) { + log.warn("Not saving " + url + " as the site's absolute URL " + + "(site.absoluteurl) because it isn't a public host name. " + + "Set \"Absolute URL to site\" under Server " + + "Administration > Configuration."); + } + return false; + } PropertiesManager pmgr = WebloggerFactory.getWeblogger().getPropertiesManager(); RuntimeConfigProperty prop = pmgr.getProperty("site.absoluteurl"); String current = prop == null ? null : prop.getValue(); @@ -357,6 +375,43 @@ public static boolean saveAbsoluteContextURLIfUnset(String url) } + /** + * True if the url's host looks like a public name for the site, and so + * may be saved automatically. Loopback and private addresses, and host + * names without a dot (such as "localhost" or the name of a proxy's + * backend), are left for an administrator to set. + */ + static boolean isPublicSiteURL(String url) { + String host; + try { + host = new URI(url).getHost(); + } catch (URISyntaxException e) { + return false; + } + if (host == null) { + return false; + } + host = host.toLowerCase(Locale.ROOT); + if (host.startsWith("[") && host.endsWith("]")) { + host = host.substring(1, host.length() - 1); + } + if (InetAddressValidator.getInstance().isValid(host)) { + try { + // an address literal, so this doesn't look anything up + InetAddress address = InetAddress.getByName(host); + byte[] bytes = address.getAddress(); + return !(address.isLoopbackAddress() || address.isAnyLocalAddress() + || address.isLinkLocalAddress() || address.isSiteLocalAddress() + || (address instanceof Inet6Address && (bytes[0] & 0xfe) == 0xfc)); + } catch (UnknownHostException e) { + return false; + } + } + return host.indexOf('.') > 0 && !host.endsWith(".") + && !host.endsWith(".localhost") && !host.endsWith(".local"); + } + + /** * Clear the caches of rendered content, whose links may have been built * from the url of a request. diff --git a/app/src/test/java/org/apache/roller/weblogger/config/SiteUrlForAdminTest.java b/app/src/test/java/org/apache/roller/weblogger/config/SiteUrlForAdminTest.java index 481d4027e..1e221c1eb 100644 --- a/app/src/test/java/org/apache/roller/weblogger/config/SiteUrlForAdminTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/config/SiteUrlForAdminTest.java @@ -132,4 +132,24 @@ void aSiteUrlSavedByAnotherRequestIsKept() throws Exception { "https://blog.example.org/roller")); verify(properties, never()).saveProperty(any()); } + + @Test + void localAndInternalHostsAreNotSaved() throws Exception { + for (String url : List.of("http://localhost:8080/roller", "http://app.localhost/roller", + "http://127.0.0.1/roller", "http://[::1]:8080/roller", "http://10.0.0.5/roller", + "http://192.168.1.20:8080", "http://[fd00::1]/roller", "http://roller:8080/roller", + "http://blog.local/roller")) { + assertFalse(WebloggerRuntimeConfig.saveAbsoluteContextURLIfUnset(url), url); + } + verify(properties, never()).saveProperty(any()); + verify(properties, never()).compareAndSetProperty(any(), any(), any()); + } + + @Test + void publicHostsMaySaveTheSiteUrl() { + for (String url : List.of("https://blog.example.org/roller", "http://93.184.215.14:8080", + "https://[2001:db8::1]/roller")) { + assertTrue(WebloggerRuntimeConfig.isPublicSiteURL(url), url); + } + } } From e709ce4b5626af88617196f106e87e62fa9b1fc0 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Tue, 17 Nov 2026 20:16:32 -0700 Subject: [PATCH 07/10] Name the Server Admin tab as the UI does in site URL messages The log and error messages about an unset site URL now point to Server Admin > Configuration, matching the tab labels. --- .../roller/weblogger/config/WebloggerRuntimeConfig.java | 4 ++-- .../roller/weblogger/planet/tasks/SyncWebsitesTask.java | 2 +- .../apache/roller/weblogger/ui/struts2/core/Install.java | 2 +- .../java/org/apache/roller/weblogger/util/MailUtil.java | 6 +++--- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java b/app/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java index 5ec8b9ad4..47ab9726a 100644 --- a/app/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java +++ b/app/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java @@ -321,7 +321,7 @@ public static String getAbsoluteContextURL() { log.warn("The site's absolute URL (site.absoluteurl) is not set, so " + "links in emails and feeds will use the host name of each " + "request. Set \"Absolute URL to site\" under Server " - + "Administration > Configuration."); + + "Admin > Configuration."); } RequestURLs request = requestURLs.get(); @@ -352,7 +352,7 @@ public static boolean saveAbsoluteContextURLIfUnset(String url) log.warn("Not saving " + url + " as the site's absolute URL " + "(site.absoluteurl) because it isn't a public host name. " + "Set \"Absolute URL to site\" under Server " - + "Administration > Configuration."); + + "Admin > Configuration."); } return false; } diff --git a/app/src/main/java/org/apache/roller/weblogger/planet/tasks/SyncWebsitesTask.java b/app/src/main/java/org/apache/roller/weblogger/planet/tasks/SyncWebsitesTask.java index ec1428017..c6b5de4e7 100644 --- a/app/src/main/java/org/apache/roller/weblogger/planet/tasks/SyncWebsitesTask.java +++ b/app/src/main/java/org/apache/roller/weblogger/planet/tasks/SyncWebsitesTask.java @@ -153,7 +153,7 @@ public void runTask() { if (!WebloggerRuntimeConfig.isAbsoluteContextURLSet()) { log.warn("Not syncing local weblogs with planet subscriptions because " + "the site's absolute URL is not set. Set it under Server " - + "Administration > Configuration."); + + "Admin > Configuration."); return; } diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Install.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Install.java index f0f2ecb34..b91f701a9 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Install.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Install.java @@ -222,7 +222,7 @@ private void saveSiteUrlIfUnset() { } } catch (Exception e) { log.warn("Could not save site.absoluteurl; set it under Server " - + "Administration > Configuration", e); + + "Admin > Configuration", e); } } diff --git a/app/src/main/java/org/apache/roller/weblogger/util/MailUtil.java b/app/src/main/java/org/apache/roller/weblogger/util/MailUtil.java index cda484785..617c23afe 100644 --- a/app/src/main/java/org/apache/roller/weblogger/util/MailUtil.java +++ b/app/src/main/java/org/apache/roller/weblogger/util/MailUtil.java @@ -97,7 +97,7 @@ public static void sendPendingEntryNotice(WeblogEntry entry) throws WebloggerExc if (!canLinkToSite()) { log.warn("No email was sent about the pending entry \"" + entry.getTitle() + "\" because the site's absolute URL is not set. Set it under " - + "Server Administration > Configuration."); + + "Server Admin > Configuration."); return; } @@ -173,7 +173,7 @@ public static void sendWeblogInvitation(Weblog website, User user) if (!canLinkToSite()) { throw new WebloggerException("The invitation was saved, but no email " + "was sent because the site's absolute URL is not set. An " - + "administrator can set it under Server Administration > " + + "administrator can set it under Server Admin > " + "Configuration."); } @@ -236,7 +236,7 @@ public static void sendUserActivationEmail(User user) if (!canLinkToSite()) { throw new WebloggerException("No activation email was sent because " + "the site's absolute URL is not set. Set it under Server " - + "Administration > Configuration."); + + "Admin > Configuration."); } try { From e64f886243ed0456fef21aa2aa1a3b8fb9319e10 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Tue, 17 Nov 2026 20:30:14 -0700 Subject: [PATCH 08/10] Set the site URL in the local planet refresh test The planet sync task and local feed fetcher now wait for site.absoluteurl, so the test sets it, as a configured site would, and clears it afterwards. --- .../business/PlanetManagerLocalTest.java | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/app/src/test/java/org/apache/roller/weblogger/business/PlanetManagerLocalTest.java b/app/src/test/java/org/apache/roller/weblogger/business/PlanetManagerLocalTest.java index 1a46e326d..ff5f29681 100644 --- a/app/src/test/java/org/apache/roller/weblogger/business/PlanetManagerLocalTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/business/PlanetManagerLocalTest.java @@ -26,6 +26,7 @@ import org.apache.roller.weblogger.config.WebloggerConfig; import org.apache.roller.weblogger.planet.tasks.RefreshRollerPlanetTask; import org.apache.roller.weblogger.planet.tasks.SyncWebsitesTask; +import org.apache.roller.weblogger.pojos.RuntimeConfigProperty; import org.apache.roller.weblogger.pojos.User; import org.apache.roller.weblogger.pojos.Weblog; import org.apache.roller.weblogger.pojos.WeblogEntry; @@ -148,7 +149,11 @@ public void testRefreshEntries() { config.when(() -> WebloggerConfig.getBooleanProperty("planet.aggregator.enabled")) .thenReturn(true); PlanetManager planet = WebloggerFactory.getWeblogger().getPlanetManager(); - + + // the planet tasks store links to local weblogs, so they wait + // until the site URL is set + setSiteUrl("https://blog.example.org/roller"); + // run sync task to fill aggregator with websites created by super SyncWebsitesTask syncTask = new SyncWebsitesTask(); syncTask.init(); @@ -171,6 +176,21 @@ public void testRefreshEntries() { e.printStackTrace(); fail(); } + finally { + try { + setSiteUrl(""); + } catch (Exception e) { + log.error(e); + } + } + } + + private static void setSiteUrl(String url) throws Exception { + PropertiesManager properties = WebloggerFactory.getWeblogger().getPropertiesManager(); + RuntimeConfigProperty prop = properties.getProperty("site.absoluteurl"); + prop.setValue(url); + properties.saveProperty(prop); + TestUtils.endSession(true); } } From 8c9ddcdc353bbb29bbeda4cd8e2237e18a83a9de Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Tue, 17 Nov 2026 21:00:08 -0700 Subject: [PATCH 09/10] Use a neutral host name in the site URL mail tests --- .../apache/roller/weblogger/util/MailUtilSiteUrlTest.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/app/src/test/java/org/apache/roller/weblogger/util/MailUtilSiteUrlTest.java b/app/src/test/java/org/apache/roller/weblogger/util/MailUtilSiteUrlTest.java index 59a547277..a7b30e96a 100644 --- a/app/src/test/java/org/apache/roller/weblogger/util/MailUtilSiteUrlTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/util/MailUtilSiteUrlTest.java @@ -67,7 +67,7 @@ */ class MailUtilSiteUrlTest { - private static final String REQUEST_URL = "http://forged.example.net"; + private static final String REQUEST_URL = "http://request-host.example.net"; private static final String SITE_URL = "https://blog.example.org"; private MockedStatic factory; @@ -175,7 +175,7 @@ void commentNotificationsLeaveOutLinksWhileTheSiteUrlIsUnset() throws Exception assertEquals(1, sent.size(), "the owner is still told about the comment"); assertTrue(sent.get(0).contains("Nice post")); - assertFalse(sent.get(0).contains("forged.example.net"), sent.get(0)); + assertFalse(sent.get(0).contains("request-host.example.net"), sent.get(0)); } @Test @@ -187,7 +187,7 @@ void commentNotificationsLinkToTheSiteUrlOnceSet() throws Exception { assertEquals(1, sent.size()); assertTrue(sent.get(0).contains(SITE_URL + "/blog/entry/first#comments"), sent.get(0)); assertTrue(sent.get(0).contains(SITE_URL + "/roller-ui/authoring/comments.rol"), sent.get(0)); - assertFalse(sent.get(0).contains("forged.example.net")); + assertFalse(sent.get(0).contains("request-host.example.net")); } @Test @@ -196,7 +196,7 @@ void approvalNotificationsLeaveOutLinksWhileTheSiteUrlIsUnset() throws Exception I18nMessages.getMessages(Locale.ENGLISH)); assertEquals(1, sent.size()); - assertFalse(sent.get(0).contains("forged.example.net"), sent.get(0)); + assertFalse(sent.get(0).contains("request-host.example.net"), sent.get(0)); } @Test From d6c2fcef4ecb7d145deb2c395710d6f75a851894 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Wed, 18 Nov 2026 21:08:54 -0700 Subject: [PATCH 10/10] Report an unset site URL honestly when adding local feeds and registering Adding a weblogger: planet subscription while the site URL is unset now tells the administrator to set the URL first instead of failing with a NullPointerException. The background updater still skips local feeds quietly. The subscription page also shows the message of a fetcher error that has no wrapped cause, rather than "null". When activation emails are required but can't be sent because the site URL is unset, registration is refused before the account is saved, so the username isn't taken by an account that can never be activated. The first administrator is still let through. If the activation email fails for any other reason, the welcome page shows an error instead of telling the visitor to check their email. Saving the site URL for the first administrator's registration and on an administrator's request is now best-effort for unchecked exceptions too, such as a lock timeout, as it already is in the installer. The concurrent site URL test restores the original value in a finally block, and the later-registrations test also asserts that compareAndSetProperty is not called. --- .../config/WebloggerRuntimeConfig.java | 3 +- .../business/WebloggerRomeFeedFetcher.java | 17 ++++++ .../weblogger/planet/ui/PlanetGroupSubs.java | 4 +- .../weblogger/ui/struts2/core/Register.java | 38 ++++++++++-- .../resources/ApplicationResources.properties | 6 ++ .../weblogger/business/PropertiesTest.java | 6 +- .../weblogger/config/SiteUrlForAdminTest.java | 13 ++++ .../planet/business/PlanetSiteUrlTest.java | 45 ++++++++++++++ .../ui/struts2/core/RegisterSiteUrlTest.java | 59 ++++++++++++++++++- 9 files changed, 181 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java b/app/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java index 47ab9726a..02e142da5 100644 --- a/app/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java +++ b/app/src/main/java/org/apache/roller/weblogger/config/WebloggerRuntimeConfig.java @@ -295,7 +295,8 @@ public static void saveAbsoluteContextURLForAdmin(User user) { if (request != null && saveAbsoluteContextURLIfUnset(request.requestURL)) { WebloggerFactory.getWeblogger().flush(); } - } catch (WebloggerException e) { + } catch (Exception e) { + // a lock timeout, for one, is unchecked; the request goes on log.warn("Could not save site.absoluteurl", e); } } diff --git a/app/src/main/java/org/apache/roller/weblogger/planet/business/WebloggerRomeFeedFetcher.java b/app/src/main/java/org/apache/roller/weblogger/planet/business/WebloggerRomeFeedFetcher.java index 361c81ecd..a54df9cfd 100644 --- a/app/src/main/java/org/apache/roller/weblogger/planet/business/WebloggerRomeFeedFetcher.java +++ b/app/src/main/java/org/apache/roller/weblogger/planet/business/WebloggerRomeFeedFetcher.java @@ -60,6 +60,23 @@ public WebloggerRomeFeedFetcher() { } + /** + * Fetch a feed for a new subscription. Unlike the updater's fetch, which + * quietly skips local weblogs until site.absoluteurl is set, this says + * why a local weblog can't be added yet. + */ + @Override + public Subscription fetchSubscription(String feedURL) throws FetcherException { + if (feedURL != null && feedURL.startsWith("weblogger:") + && !WebloggerRuntimeConfig.isAbsoluteContextURLSet()) { + throw new FetcherException("This site's weblogs can't be added " + + "until the site's absolute URL is set. Set it under " + + "Server Admin > Configuration."); + } + return super.fetchSubscription(feedURL); + } + + @Override public Subscription fetchSubscription(String feedURL, Date lastModified) throws FetcherException { diff --git a/app/src/main/java/org/apache/roller/weblogger/planet/ui/PlanetGroupSubs.java b/app/src/main/java/org/apache/roller/weblogger/planet/ui/PlanetGroupSubs.java index f4f7ed216..f95d06687 100644 --- a/app/src/main/java/org/apache/roller/weblogger/planet/ui/PlanetGroupSubs.java +++ b/app/src/main/java/org/apache/roller/weblogger/planet/ui/PlanetGroupSubs.java @@ -227,7 +227,9 @@ public String saveSubscription() { addMessage("planetSubscription.success.saved"); } catch (FetcherException ex) { - addError("planetGroupSubs.error.fetchingFeed", ex.getRootCauseMessage()); + // not every fetcher error wraps another exception + addError("planetGroupSubs.error.fetchingFeed", ex.getRootCause() != null + ? ex.getRootCauseMessage() : ex.getMessage()); } catch (RollerException ex) { log.error("Unexpected error saving subscription", ex); diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Register.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Register.java index cb80f817b..ee3384249 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Register.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Register.java @@ -220,6 +220,21 @@ public String save() { // are we using email activation? boolean activationEnabled = WebloggerRuntimeConfig.getBooleanProperty( "user.account.email.activation"); + + // the activation email links to the site, so without a site + // url it can't be sent and the account could never be + // activated. The first administrator is let through, as + // nobody else can set the url. + if (activationEnabled && !initialAdmin + && !WebloggerRuntimeConfig.isAbsoluteContextURLSet()) { + log.warn("A registration was refused because activation " + + "emails can't be sent until the site's absolute " + + "URL is set. Set it under Server Admin > " + + "Configuration."); + addError("Register.error.activationUnavailable"); + return INPUT; + } + if (activationEnabled) { // User account will be enabled after the activation process ud.setEnabled(Boolean.FALSE); @@ -247,8 +262,7 @@ public String save() { // the first administrator is the one setting up the site, so // take the site's url from this request if none is configured if (initialAdmin) { - WebloggerRuntimeConfig.saveAbsoluteContextURLIfUnset( - InitFilter.getAbsoluteUrl(getServletRequest())); + saveSiteUrlIfUnset(); } WebloggerFactory.getWeblogger().flush(); @@ -279,6 +293,20 @@ public String save() { return INPUT; } + /** + * Failing to save the site's url doesn't stop the registration; an + * administrator can set it later. + */ + private void saveSiteUrlIfUnset() { + try { + WebloggerRuntimeConfig.saveAbsoluteContextURLIfUnset( + InitFilter.getAbsoluteUrl(getServletRequest())); + } catch (Exception e) { + log.warn("Could not save site.absoluteurl; set it under Server " + + "Admin > Configuration", e); + } + } + private String retryActivationCode(UserManager mgr, String inActivationCode) throws WebloggerException { if (mgr.getUserByActivationCode(inActivationCode) != null) { // In the *extremely* unlikely event that we generate an @@ -308,11 +336,13 @@ private void sendActivationMailIfNeeded(User ud, boolean activationEnabled) { try { // send activation mail to the user MailUtil.sendUserActivationEmail(ud); + setActivationStatus("pending"); } catch (WebloggerException ex) { log.error("Error sending activation email to - " + ud.getEmailAddress(), ex); + // the account exists but can't be activated without the email + addError("Register.error.activationNotSent"); + setActivationStatus("error"); } - - setActivationStatus("pending"); } } diff --git a/app/src/main/resources/ApplicationResources.properties b/app/src/main/resources/ApplicationResources.properties index b55815559..9722a4557 100644 --- a/app/src/main/resources/ApplicationResources.properties +++ b/app/src/main/resources/ApplicationResources.properties @@ -1537,6 +1537,12 @@ Register.error.localeNull=Locale is a required field Register.error.localeSize=Locale cannot be more than 20 characters Register.error.timeZoneNull=Time Zone is a required field Register.error.timeZoneSize=Time Zone cannot be more than 20 characters +Register.error.activationUnavailable=New accounts cannot be created right now \ +because this site cannot send activation emails yet. Please contact the site \ +administrator. +Register.error.activationNotSent=Your account was created, but the activation \ +email could not be sent, so you cannot log in yet. Please contact the site \ +administrator. # ------------------------------------------------------------------ Weblog edit diff --git a/app/src/test/java/org/apache/roller/weblogger/business/PropertiesTest.java b/app/src/test/java/org/apache/roller/weblogger/business/PropertiesTest.java index bf4d987d2..55f30f0b4 100644 --- a/app/src/test/java/org/apache/roller/weblogger/business/PropertiesTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/business/PropertiesTest.java @@ -159,11 +159,13 @@ public void onlyOneConcurrentRequestSavesTheSiteUrl() throws Exception { .getPropertiesManager().getProperty("site.absoluteurl"); assertEquals(firstSaved ? "https://first.example.org" : "https://second.example.org", saved.getValue()); + } finally { + executor.shutdownNow(); + RuntimeConfigProperty saved = WebloggerFactory.getWeblogger() + .getPropertiesManager().getProperty("site.absoluteurl"); saved.setValue(original); WebloggerFactory.getWeblogger().getPropertiesManager().saveProperty(saved); TestUtils.endSession(true); - } finally { - executor.shutdownNow(); } } diff --git a/app/src/test/java/org/apache/roller/weblogger/config/SiteUrlForAdminTest.java b/app/src/test/java/org/apache/roller/weblogger/config/SiteUrlForAdminTest.java index 1e221c1eb..32d31ee71 100644 --- a/app/src/test/java/org/apache/roller/weblogger/config/SiteUrlForAdminTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/config/SiteUrlForAdminTest.java @@ -31,6 +31,7 @@ import org.mockito.ArgumentCaptor; import org.mockito.MockedStatic; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -105,6 +106,18 @@ void aConfiguredSiteUrlIsKept() throws Exception { verify(properties, never()).saveProperty(any()); } + @Test + void aFailureToSaveDoesNotFailTheAdministratorsRequest() throws Exception { + when(properties.getProperty("site.absoluteurl")).thenReturn( + new RuntimeConfigProperty("site.absoluteurl", "")); + when(properties.compareAndSetProperty(eq("site.absoluteurl"), any(), any())) + .thenThrow(new RuntimeException("lock timeout")); + User admin = mock(User.class); + when(admin.hasGlobalPermission("admin")).thenReturn(true); + + assertDoesNotThrow(() -> WebloggerRuntimeConfig.saveAbsoluteContextURLForAdmin(admin)); + } + @Test void anEmptySiteUrlIsOnlySavedIfStillEmpty() throws Exception { when(properties.getProperty("site.absoluteurl")).thenReturn( diff --git a/app/src/test/java/org/apache/roller/weblogger/planet/business/PlanetSiteUrlTest.java b/app/src/test/java/org/apache/roller/weblogger/planet/business/PlanetSiteUrlTest.java index d3ee403d9..65af00952 100644 --- a/app/src/test/java/org/apache/roller/weblogger/planet/business/PlanetSiteUrlTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/planet/business/PlanetSiteUrlTest.java @@ -17,18 +17,26 @@ package org.apache.roller.weblogger.planet.business; +import java.util.List; + +import org.apache.roller.planet.business.PlanetManager; +import org.apache.roller.planet.business.fetcher.FetcherException; import org.apache.roller.weblogger.business.PropertiesManager; import org.apache.roller.weblogger.business.Weblogger; import org.apache.roller.weblogger.business.WebloggerFactory; import org.apache.roller.weblogger.config.WebloggerConfig; import org.apache.roller.weblogger.planet.tasks.SyncWebsitesTask; +import org.apache.roller.weblogger.planet.ui.PlanetGroupSubs; import org.apache.roller.weblogger.pojos.RuntimeConfigProperty; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.never; @@ -41,6 +49,10 @@ */ class PlanetSiteUrlTest { + private static final String SITE_URL_UNSET = "This site's weblogs can't be " + + "added until the site's absolute URL is set. Set it under Server " + + "Admin > Configuration."; + private MockedStatic factory; private Weblogger weblogger; @@ -66,6 +78,39 @@ void localFeedsAreNotFetchedWhileTheSiteUrlIsUnset() throws Exception { verify(weblogger, never()).getWeblogManager(); } + @Test + void addingALocalFeedSaysTheSiteUrlMustBeSetFirst() throws Exception { + FetcherException ex = assertThrows(FetcherException.class, + () -> new WebloggerRomeFeedFetcher().fetchSubscription("weblogger:blog")); + assertEquals(SITE_URL_UNSET, ex.getMessage()); + verify(weblogger, never()).getWeblogManager(); + } + + @Test + void theAdministratorAddingALocalFeedIsToldToSetTheSiteUrl() throws Exception { + PlanetManager planets = mock(PlanetManager.class); + when(weblogger.getPlanetManager()).thenReturn(planets); + when(weblogger.getFeedFetcher()).thenReturn(new WebloggerRomeFeedFetcher()); + + PlanetGroupSubs action = new PlanetGroupSubs() { + @Override + protected boolean isPostRequest() { + return true; + } + + @Override + public String getText(String key, String defaultValue, String arg) { + return key + ": " + arg; + } + }; + action.setSubUrl("weblogger:blog"); + + assertEquals("list", action.saveSubscription()); + assertEquals(List.of("planetGroupSubs.error.fetchingFeed: " + SITE_URL_UNSET), + List.copyOf(action.getActionErrors())); + verify(planets, never()).saveSubscription(any()); + } + @Test void weblogsAreNotSyncedWhileTheSiteUrlIsUnset() { try (MockedStatic config = mockStatic(WebloggerConfig.class)) { diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/RegisterSiteUrlTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/RegisterSiteUrlTest.java index 28e6aa51a..2be50829a 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/RegisterSiteUrlTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/RegisterSiteUrlTest.java @@ -39,11 +39,17 @@ import org.springframework.security.crypto.password.NoOpPasswordEncoder; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -58,11 +64,12 @@ class RegisterSiteUrlTest { private MockedStatic bootstrap; private MockedStatic context; private PropertiesManager properties; + private UserManager users; @BeforeEach void setUp() throws Exception { properties = mock(PropertiesManager.class); - UserManager users = mock(UserManager.class); + users = mock(UserManager.class); Weblogger weblogger = mock(Weblogger.class); when(weblogger.getPropertiesManager()).thenReturn(properties); when(weblogger.getUserManager()).thenReturn(users); @@ -96,7 +103,8 @@ private static Register register(String scheme, String host, int port) { scheme + "://" + host + ":" + port + "/roller/roller-ui/register!save.rol")); when(request.getSession()).thenReturn(mock(HttpSession.class)); - Register action = new Register(); + Register action = spy(new Register()); + doAnswer(call -> call.getArgument(0)).when(action).getText(anyString()); action.withServletRequest(request); action.getBean().setUserName("admin"); action.getBean().setScreenName("Admin"); @@ -145,5 +153,52 @@ void laterRegistrationsDoNotRecordSiteUrl() throws Exception { assertEquals("success", register("http", "other.example.net", 80).save()); assertTrue(savedSiteUrls().isEmpty(), "only the initial administrator's registration may set the URL"); + verify(properties, never()).compareAndSetProperty( + eq("site.absoluteurl"), any(), any()); + } + + @Test + void firstAdministratorIsRegisteredEvenIfSiteUrlCannotBeSaved() throws Exception { + bootstrap.when(BootstrapSecurity::isCompleted).thenReturn(false); + bootstrap.when(() -> BootstrapSecurity.isValid(any())).thenReturn(true); + when(properties.getProperty("site.absoluteurl")) + .thenReturn(new RuntimeConfigProperty("site.absoluteurl", "")); + when(properties.compareAndSetProperty(eq("site.absoluteurl"), any(), any())) + .thenThrow(new RuntimeException("lock timeout")); + + assertEquals("success", register("https", "blog.example.org", 443).save()); + verify(users).addUser(any()); + } + + @Test + void registrationIsRefusedWhileActivationEmailsCannotLinkToTheSite() throws Exception { + bootstrap.when(BootstrapSecurity::isCompleted).thenReturn(true); + when(properties.getProperty("user.account.email.activation")).thenReturn( + new RuntimeConfigProperty("user.account.email.activation", "true")); + when(properties.getProperty("site.absoluteurl")) + .thenReturn(new RuntimeConfigProperty("site.absoluteurl", "")); + + Register action = register("https", "blog.example.org", 443); + assertEquals("input", action.save()); + assertEquals(List.of("Register.error.activationUnavailable"), + List.copyOf(action.getActionErrors())); + assertNull(action.getActivationStatus()); + verify(users, never()).addUser(any()); + } + + @Test + void activationIsNotReportedPendingWhenNoEmailWasSent() throws Exception { + // the first administrator is never refused, and no mail is configured + bootstrap.when(BootstrapSecurity::isCompleted).thenReturn(false); + bootstrap.when(() -> BootstrapSecurity.isValid(any())).thenReturn(true); + when(properties.getProperty("user.account.email.activation")).thenReturn( + new RuntimeConfigProperty("user.account.email.activation", "true")); + + Register action = register("https", "blog.example.org", 443); + assertEquals("success", action.save()); + verify(users).addUser(any()); + assertEquals("error", action.getActivationStatus()); + assertEquals(List.of("Register.error.activationNotSent"), + List.copyOf(action.getActionErrors())); } }