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 7aa2064758..2139d1ecfc 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 @@ -41,7 +41,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/business/plugins/entry/SmileysPlugin.java b/app/src/main/java/org/apache/roller/weblogger/business/plugins/entry/SmileysPlugin.java index 2b4acd29c7..6f9630881a 100644 --- a/app/src/main/java/org/apache/roller/weblogger/business/plugins/entry/SmileysPlugin.java +++ b/app/src/main/java/org/apache/roller/weblogger/business/plugins/entry/SmileysPlugin.java @@ -39,6 +39,8 @@ public class SmileysPlugin implements WeblogEntryPlugin { // public for tests public static Pattern[] smileyPatterns = new Pattern[0]; + // each img tag after its src's site URL, which comes from the request + // being rendered static String[] imageTags = new String[0]; private static final Properties smileyDefs = new Properties(); @@ -75,15 +77,14 @@ public String getDescription() { /* * Convert the SmileyDefs into RegEx patterns and img tags for - * later use. Need an HttpServletRequest though so that we can - * get the ServletContext Path. But only do it once. + * later use. But only do it once. The site URL in each tag is added + * when rendering, since while site.absoluteurl is unset it depends on + * the request. */ @Override public synchronized void init(Weblog website) throws WebloggerException { // don't do this work if Smileys already loaded if (SmileysPlugin.smileyPatterns.length < 1) { - String baseURL = WebloggerRuntimeConfig.getAbsoluteContextURL(); - Pattern[] tempP = new Pattern[SmileysPlugin.smileyDefs.size()]; String[] tempS = new String[SmileysPlugin.smileyDefs.size()]; log.debug("# smileys: " + smileyDefs.size()); @@ -93,8 +94,7 @@ public synchronized void init(Weblog website) throws WebloggerException { String smiley = (String)enum1.nextElement(); String smileyAlt = htmlEscape(smiley); tempP[count] = Pattern.compile(regexEscape(smiley)); - tempS[count] = "\"" requestURLs = + new ThreadLocal<>(); + private static final AtomicBoolean absoluteURLWarningLogged = + new AtomicBoolean(false); + private static final AtomicBoolean localURLWarningLogged = + new AtomicBoolean(false); // prevent instantiations @@ -168,34 +190,240 @@ public static String getRuntimeConfigDefsAsString() { /** - * Special method which sets the non-persisted absolute url to this site. + * 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 + * 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) { + requestURLs.set(new RequestURLs(url)); } - - + + + /** + * Forget the urls of the request handled on this thread. + */ + public static void clearRequestAbsoluteContextURL() { + 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 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, 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) { + if (key == null || configuredAbsoluteContextURL() != null) { + return key; + } + RequestURLs request = requestURLs.get(); + if (request == null || request.requestURL == null) { + return null; + } + return key + "|" + request.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) { + if (liveAbsoluteContextURL() != null || user == null + || !user.hasGlobalPermission("admin")) { + return; + } + RequestURLs request = requestURLs.get(); + try { + if (request != null && saveAbsoluteContextURLIfUnset(request.requestURL)) { + WebloggerFactory.getWeblogger().flush(); + } + } catch (Exception e) { + // a lock timeout, for one, is unchecked; the request goes on + log.warn("Could not save site.absoluteurl", e); + } + } + + /** * 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() { // 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; } - - 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 " + + "Admin > Configuration."); + } + + RequestURLs request = requestURLs.get(); + return request == null ? null : request.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. + * + * 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) + throws WebloggerException { + + 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 " + + "Admin > Configuration."); + } + return false; + } + PropertiesManager pmgr = WebloggerFactory.getWeblogger().getPropertiesManager(); + RuntimeConfigProperty prop = pmgr.getProperty("site.absoluteurl"); + String current = prop == null ? null : prop.getValue(); + if (current != null && !current.isBlank()) { + return false; + } + if (prop == null) { + // 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; + } + clearRenderingCaches(); + log.info("Set site.absoluteurl to " + url); + return true; } + /** + * 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. + */ + 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 2645badf21..cd3dd48a2f 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 @@ -35,7 +35,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/planet/business/WebloggerRomeFeedFetcher.java b/app/src/main/java/org/apache/roller/weblogger/planet/business/WebloggerRomeFeedFetcher.java index 076ad46352..2d627743f2 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 @@ -59,6 +59,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 { @@ -74,6 +91,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 80f4b23789..373e4dcce4 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 @@ -39,6 +39,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; @@ -146,6 +147,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 " + + "Admin > Configuration."); + return; + } + log.info("Syncing local weblogs with planet subscriptions list"); try { 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 b4959f5471..b6c3462834 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 @@ -213,7 +213,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/core/filters/InitFilter.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/filters/InitFilter.java index 554ccc6beb..2087f0a00b 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 @@ -19,6 +19,7 @@ package org.apache.roller.weblogger.ui.core.filters; import java.io.IOException; +import java.util.Locale; import javax.servlet.Filter; import javax.servlet.FilterChain; @@ -34,9 +35,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" */ @@ -44,48 +50,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 @@ -96,42 +92,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 9ea6214619..2672e8b225 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 @@ -26,6 +26,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; @@ -97,8 +98,9 @@ public static PlanetCache getInstance() { public Object get(String key) { + key = WebloggerRuntimeConfig.cacheKey(key); - if (!cacheEnabled) { + if (!cacheEnabled || key == null) { return null; } @@ -115,8 +117,9 @@ public Object get(String key) { public void put(String key, Object value) { + key = WebloggerRuntimeConfig.cacheKey(key); - if (!cacheEnabled) { + if (!cacheEnabled || key == null) { return; } @@ -126,8 +129,9 @@ 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 74e01893b7..9c29c52137 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 @@ -103,8 +103,9 @@ public static SiteWideCache getInstance() { public Object get(String key) { + key = WebloggerRuntimeConfig.cacheKey(key); - if (!cacheEnabled) { + if (!cacheEnabled || key == null) { return null; } @@ -121,8 +122,9 @@ public Object get(String key) { public void put(String key, Object value) { + key = WebloggerRuntimeConfig.cacheKey(key); - if (!cacheEnabled) { + if (!cacheEnabled || key == null) { return; } @@ -132,8 +134,9 @@ 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 98baa89b4e..e020b85ba4 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 @@ -26,6 +26,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; @@ -102,6 +103,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 14087b57ba..a6fe2c1c64 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 @@ -27,6 +27,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; @@ -88,8 +89,9 @@ public static WeblogFeedCache getInstance() { public Object get(String key, long lastModified) { + key = WebloggerRuntimeConfig.cacheKey(key); - if (!cacheEnabled) { + if (!cacheEnabled || key == null) { return null; } @@ -115,8 +117,9 @@ 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; } @@ -126,8 +129,9 @@ 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 9edadf97c8..ee4b6191f9 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 @@ -27,6 +27,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; @@ -87,8 +88,9 @@ public static WeblogPageCache getInstance() { public Object get(String key, long lastModified) { + key = WebloggerRuntimeConfig.cacheKey(key); - if (!cacheEnabled) { + if (!cacheEnabled || key == null) { return null; } @@ -113,8 +115,9 @@ 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; } @@ -124,8 +127,9 @@ 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/struts2/core/Install.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Install.java index 4ccc4d5105..0c7bd70f03 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 @@ -23,6 +23,8 @@ import java.sql.Connection; import java.util.List; +import javax.servlet.http.HttpServletRequest; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.roller.weblogger.WebloggerException; @@ -30,9 +32,11 @@ 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.struts2.ServletActionContext; +import org.apache.roller.weblogger.ui.core.filters.InitFilter; +import org.apache.struts2.interceptor.ServletRequestAware; import org.apache.roller.weblogger.ui.core.security.BootstrapSecurity; @@ -40,7 +44,7 @@ * Walk user through install process. */ // TODO: make this work @AllowedMethods({"execute","create","upgrade","bootstrap"}) -public class Install extends UIAction { +public class Install extends UIAction implements ServletRequestAware { private static Log log = LogFactory.getLog(Install.class); @@ -54,7 +58,17 @@ public class Install extends UIAction { private boolean success = false; private List messages = null; private String databaseName = "Unknown"; + private HttpServletRequest servletRequest = null; + + protected HttpServletRequest getServletRequest() { + return servletRequest; + } + + @Override + public void setServletRequest(HttpServletRequest servletRequest) { + this.servletRequest = servletRequest; + } @Override public void setPageTitle(String pageTitle) { @@ -115,7 +129,7 @@ public String execute() { public String create() { - if (!BootstrapSecurity.isValid(ServletActionContext.getRequest())) return BOOTSTRAP; + if (!BootstrapSecurity.isValid(getServletRequest())) return BOOTSTRAP; if (WebloggerFactory.isBootstrapped()) { return SUCCESS; @@ -136,7 +150,7 @@ public String create() { public String upgrade() { - if (!BootstrapSecurity.isValid(ServletActionContext.getRequest())) return BOOTSTRAP; + if (!BootstrapSecurity.isValid(getServletRequest())) return BOOTSTRAP; if (WebloggerFactory.isBootstrapped()) { return SUCCESS; @@ -157,7 +171,7 @@ public String upgrade() { public String bootstrap() { - if (!BootstrapSecurity.isValid(ServletActionContext.getRequest())) return BOOTSTRAP; + if (!BootstrapSecurity.isValid(getServletRequest())) return BOOTSTRAP; log.info("ENTERING"); if (WebloggerFactory.isBootstrapped()) { @@ -178,6 +192,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 +226,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 " + + "Admin > 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 8d9c85050c..0263f348c9 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 @@ -35,6 +35,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(); @@ -218,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); @@ -242,6 +259,12 @@ 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) { + saveSiteUrlIfUnset(); + } + WebloggerFactory.getWeblogger().flush(); if (!BootstrapSecurity.isCompleted()) BootstrapSecurity.complete(); @@ -270,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 @@ -299,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/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 9eb5009573..689d5387b6 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 @@ -24,6 +24,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; @@ -68,6 +69,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/main/java/org/apache/roller/weblogger/util/MailUtil.java b/app/src/main/java/org/apache/roller/weblogger/util/MailUtil.java index eeedc9e322..afb8c60917 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 @@ -71,6 +71,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. */ @@ -82,6 +92,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 Admin > Configuration."); + return; + } try { WeblogManager wmgr = WebloggerFactory.getWeblogger().getWeblogManager(); @@ -151,6 +168,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 Admin > " + + "Configuration."); + } try { String from = website.getEmailAddress(); @@ -207,6 +231,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 " + + "Admin > Configuration."); + } try { ResourceBundle resources = ResourceBundle.getBundle( @@ -334,19 +364,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 @@ -399,19 +437,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(""); } @@ -533,9 +576,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/main/resources/ApplicationResources.properties b/app/src/main/resources/ApplicationResources.properties index eb6a304856..690a8746bc 100644 --- a/app/src/main/resources/ApplicationResources.properties +++ b/app/src/main/resources/ApplicationResources.properties @@ -1525,6 +1525,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/PlanetManagerLocalTest.java b/app/src/test/java/org/apache/roller/weblogger/business/PlanetManagerLocalTest.java index 1a46e326d4..ff5f29681b 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); } } 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 facccc4c50..0ba3673e09 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 @@ -21,6 +21,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; @@ -129,6 +130,61 @@ 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()); + } finally { + executor.shutdownNow(); + RuntimeConfigProperty saved = WebloggerFactory.getWeblogger() + .getPropertiesManager().getProperty("site.absoluteurl"); + saved.setValue(original); + WebloggerFactory.getWeblogger().getPropertiesManager().saveProperty(saved); + TestUtils.endSession(true); + } + } + + 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/business/plugins/entry/SmileysPluginSiteUrlTest.java b/app/src/test/java/org/apache/roller/weblogger/business/plugins/entry/SmileysPluginSiteUrlTest.java new file mode 100644 index 0000000000..571d0eb685 --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/business/plugins/entry/SmileysPluginSiteUrlTest.java @@ -0,0 +1,91 @@ +/* + * 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.business.plugins.entry; + +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.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.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + +/** + * Emoticon images link to the site URL of the request being rendered, not to + * the one seen by whichever request first loaded the plugin. + */ +class SmileysPluginSiteUrlTest { + + private MockedStatic factory; + + @BeforeEach + void setUp() throws Exception { + PropertiesManager properties = mock(PropertiesManager.class); + 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); + } + + @AfterEach + void tearDown() { + WebloggerRuntimeConfig.clearRequestAbsoluteContextURL(); + factory.close(); + } + + private static String renderDuring(String requestURL) throws Exception { + WebloggerRuntimeConfig.setRequestAbsoluteContextURL(requestURL); + try { + SmileysPlugin plugin = new SmileysPlugin(); + plugin.init(null); + return plugin.render(null, "Hello :-)"); + } finally { + WebloggerRuntimeConfig.clearRequestAbsoluteContextURL(); + } + } + + @Test + void eachRequestGetsItsOwnHost() throws Exception { + String first = renderDuring("http://first.example.com"); + String second = renderDuring("http://second.example.com"); + + assertTrue(first.contains("src=\"http://first.example.com/images/smileys/smile.gif\""), first); + assertTrue(second.contains("src=\"http://second.example.com/images/smileys/smile.gif\""), second); + assertFalse(second.contains("first.example.com"), second); + } + + @Test + void renderingOutsideARequestDoesNotLinkToNull() throws Exception { + SmileysPlugin plugin = new SmileysPlugin(); + plugin.init(null); + String text = plugin.render(null, "Hello :-)"); + + assertTrue(text.contains("/images/smileys/smile.gif"), text); + assertFalse(text.contains("null/"), text); + } +} 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 0000000000..32d31ee71b --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/config/SiteUrlForAdminTest.java @@ -0,0 +1,168 @@ +/* + * 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.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; +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; +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()); + } + + @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( + 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()); + } + + @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); + } + } +} 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 0000000000..8fc3031136 --- /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")); + } +} 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 0000000000..65af009522 --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/planet/business/PlanetSiteUrlTest.java @@ -0,0 +1,125 @@ +/* + * 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 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; +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 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; + + @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 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)) { + config.when(() -> WebloggerConfig.getBooleanProperty("planet.aggregator.enabled")) + .thenReturn(true); + + new SyncWebsitesTask().runTask(); + } + verify(weblogger, never()).getPlanetManager(); + verify(weblogger, never()).getWeblogManager(); + } +} 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 30f1a3efa6..32c9388915 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 @@ -18,9 +18,31 @@ package org.apache.roller.weblogger.ui.core.filters; +import java.util.concurrent.atomic.AtomicReference; + +import javax.servlet.FilterChain; +import javax.servlet.http.HttpServletRequest; +import javax.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; +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; /** @@ -30,48 +52,177 @@ 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 testContentBuiltFromRequestHostIsCachedPerHost() throws Exception { + String key = "InitFilterTest/" + System.nanoTime(); + AtomicReference seen = new AtomicReference<>(); + FilterChain store = (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), 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 { + 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); + new InitFilter().doFilter(request("http", SERVER_NAME, 80, "", "/"), + mock(HttpServletResponse.class), lookup); + assertNotNull(seen.get()); + } finally { + new InitFilter().doFilter(request("http", SERVER_NAME, 80, "", "/"), + mock(HttpServletResponse.class), (req, res) -> 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 de2d340eb0..dd32f6fd81 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 @@ -6,9 +6,17 @@ */ package org.apache.roller.weblogger.ui.struts2.core; +import java.util.List; +import java.util.stream.Collectors; +import javax.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.*; @@ -28,4 +36,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.setServletRequest(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 0000000000..a2571ed411 --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/RegisterSiteUrlTest.java @@ -0,0 +1,204 @@ +/* + * 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 javax.servlet.http.HttpServletRequest; +import javax.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.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; + +/** + * 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; + private UserManager users; + + @BeforeEach + void setUp() throws Exception { + properties = mock(PropertiesManager.class); + 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 = spy(new Register()); + doAnswer(call -> call.getArgument(0)).when(action).getText(anyString()); + action.setServletRequest(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"); + 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())); + } +} 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 0000000000..43b30a8cfe --- /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 javax.mail.Address; +import javax.mail.Message; +import javax.mail.Session; +import javax.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://request-host.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("request-host.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("request-host.example.net")); + } + + @Test + void approvalNotificationsLeaveOutLinksWhileTheSiteUrlIsUnset() throws Exception { + MailUtil.sendEmailApprovalNotification(pendingComment(), + I18nMessages.getMessages(Locale.ENGLISH)); + + assertEquals(1, sent.size()); + assertFalse(sent.get(0).contains("request-host.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)); + } +}