mraible commented on code in PR #167: URL: https://github.com/apache/roller/pull/167#discussion_r3891439015
########## app/src/main/java/org/apache/roller/weblogger/ui/core/filters/SaltValidator.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. For additional information regarding + * copyright in this work, please see the NOTICE file in the top level + * directory of this distribution. + */ + +package org.apache.roller.weblogger.ui.core.filters; + +import java.util.Locale; +import java.util.Objects; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.roller.weblogger.ui.core.RollerSession; +import org.apache.roller.weblogger.ui.rendering.util.cache.SaltCache; + +/** + * Shared validation for salts submitted by UI forms. + */ +public final class SaltValidator { + + private static final String MULTIPART_FORM_DATA = "multipart/form-data"; + + private SaltValidator() { + } + + /** + * Validates and consumes the salt submitted as a request parameter. + * + * @param request current request + * @return true when no Roller session is present or the submitted salt is valid + */ + public static boolean consumeSubmittedSalt(HttpServletRequest request) { + RollerSession rollerSession = RollerSession.getRollerSession(request); + if (rollerSession == null) { + return true; + } + + String userId = rollerSession.getAuthenticatedUser() != null + ? rollerSession.getAuthenticatedUser().getId() : ""; + String salt = request.getParameter("salt"); + if (salt == null) { + return false; + } + + SaltCache saltCache = SaltCache.getInstance(); + synchronized (saltCache) { + if (!Objects.equals(saltCache.get(salt), userId)) { Review Comment: Now that this is the only path, `cache.salt.size` (5000) and `cache.salt.timeout` (3600s) are user-visible limits: `LoadSaltFilter` mints a salt on every `/roller-ui` request and on every tiles FORWARD, so entries get evicted quickly on a multi-user site, and a form left open for over an hour is rejected with the entry text lost. Not a blocker, but please call it out in the description; raising the defaults would soften it. ########## app/src/main/java/org/apache/roller/weblogger/ui/struts2/util/ValidateSaltInterceptor.java: ########## @@ -0,0 +1,58 @@ +/* + * 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. For additional information regarding + * copyright in this work, please see the NOTICE file in the top level + * directory of this distribution. + */ + +package org.apache.roller.weblogger.ui.struts2.util; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.roller.weblogger.ui.core.filters.SaltValidator; +import org.apache.struts2.StrutsStatics; + +import com.opensymphony.xwork2.ActionContext; +import com.opensymphony.xwork2.ActionInvocation; +import com.opensymphony.xwork2.interceptor.AbstractInterceptor; + +/** + * Validates salts after Struts has parsed a multipart form request. + */ +public class ValidateSaltInterceptor extends AbstractInterceptor implements StrutsStatics { + + private static final long serialVersionUID = 2446434402795510394L; + private static final Log log = LogFactory.getLog(ValidateSaltInterceptor.class); + + @Override + public String intercept(ActionInvocation invocation) throws Exception { + ActionContext context = invocation.getInvocationContext(); + HttpServletRequest request = (HttpServletRequest) context.get(HTTP_REQUEST); + + if (SaltValidator.isMultipartFormPost(request) Review Comment: This runs again on every chained invocation of the same request. `bookmarksImport!save` is multipart and has `<result name="success" type="chain">bookmarks</result>`, so the second pass finds the salt already removed from `SaltCache` and throws `Security Violation` after the OPML import has been flushed. Simplest fix: after a successful `consumeSubmittedSalt`, set a request attribute (e.g. `request.setAttribute("salt.validated", Boolean.TRUE)`) and skip validation when it's present. Good candidate for a `ValidateSaltInterceptorTest` case. Related: when Struts can't parse the multipart body (over `struts.multipart.maxSize`), `MultiPartRequestWrapper` has no fields, `getParameter("salt")` is null and this throws a 500 instead of letting the `fileUpload` interceptor's size error reach the form as it does today. Checking `((MultiPartRequestWrapper) request).hasErrors()` first would keep that UX. ########## app/src/main/java/org/apache/roller/weblogger/ui/core/filters/ValidateSaltFilter.java: ########## @@ -31,53 +28,35 @@ import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; -import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.roller.weblogger.config.WebloggerConfig; -import org.apache.roller.weblogger.ui.rendering.util.cache.SaltCache; -import org.apache.roller.weblogger.ui.core.RollerSession; /** * Filter checks all POST request for presence of valid salt value and rejects those without * a salt value or with a salt value not generated by this Roller instance. */ public class ValidateSaltFilter implements Filter { private static final Log log = LogFactory.getLog(ValidateSaltFilter.class); - private Set<String> ignored = Collections.emptySet(); @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpReq = (HttpServletRequest) request; - String requestURL = httpReq.getRequestURL().toString(); - String queryString = httpReq.getQueryString(); - if (queryString != null) { - requestURL += "?" + queryString; - } - - if ("POST".equals(httpReq.getMethod()) && !isIgnoredURL(requestURL)) { - RollerSession rollerSession = RollerSession.getRollerSession(httpReq); - if (rollerSession != null) { - String userId = rollerSession.getAuthenticatedUser() != null ? rollerSession.getAuthenticatedUser().getId() : ""; - - Object saltObject = httpReq.getAttribute("salt"); // multi-form post case - String salt = saltObject != null ? saltObject.toString() : null; - salt = salt != null ? salt : httpReq.getParameter("salt"); - SaltCache saltCache = SaltCache.getInstance(); - if (salt == null || !Objects.equals(saltCache.get(salt), userId)) { - if (log.isDebugEnabled()) { - log.debug("Valid salt value not found on POST to URL : " + httpReq.getServletPath()); - } - throw new ServletException("Security Violation"); - } + if ("POST".equalsIgnoreCase(httpReq.getMethod())) { + if (SaltValidator.isMultipartFormPost(httpReq) && isStrutsAction(httpReq)) { + // Struts makes multipart parameters available after its upload + // interceptor; ValidateSaltInterceptor handles these requests. + chain.doFilter(request, response); + return; + } - // Remove salt from cache after successful validation - saltCache.remove(salt); + if (!SaltValidator.consumeSubmittedSalt(httpReq)) { Review Comment: `Comments.jsp:429` reads `#comments_salt` once and sends it on every `commentdata` AJAX POST. With the salt removed on first use, editing a second comment without reloading fails here with a 500, and the `$.ajax` call has no error handler, so the save just silently doesn't happen. `CommentDataServlet` could return a fresh salt in its JSON (the response passes through `LoadSaltFilter`, so `request.getAttribute("salt")` is available) and the JS update `#comments_salt` from it. ########## app/src/main/java/org/apache/roller/weblogger/ui/core/filters/ValidateSaltFilter.java: ########## @@ -31,53 +28,35 @@ import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; -import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.roller.weblogger.config.WebloggerConfig; -import org.apache.roller.weblogger.ui.rendering.util.cache.SaltCache; -import org.apache.roller.weblogger.ui.core.RollerSession; /** * Filter checks all POST request for presence of valid salt value and rejects those without * a salt value or with a salt value not generated by this Roller instance. */ public class ValidateSaltFilter implements Filter { private static final Log log = LogFactory.getLog(ValidateSaltFilter.class); - private Set<String> ignored = Collections.emptySet(); @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpReq = (HttpServletRequest) request; - String requestURL = httpReq.getRequestURL().toString(); - String queryString = httpReq.getQueryString(); - if (queryString != null) { - requestURL += "?" + queryString; - } - - if ("POST".equals(httpReq.getMethod()) && !isIgnoredURL(requestURL)) { - RollerSession rollerSession = RollerSession.getRollerSession(httpReq); - if (rollerSession != null) { - String userId = rollerSession.getAuthenticatedUser() != null ? rollerSession.getAuthenticatedUser().getId() : ""; - - Object saltObject = httpReq.getAttribute("salt"); // multi-form post case - String salt = saltObject != null ? saltObject.toString() : null; - salt = salt != null ? salt : httpReq.getParameter("salt"); - SaltCache saltCache = SaltCache.getInstance(); - if (salt == null || !Objects.equals(saltCache.get(salt), userId)) { - if (log.isDebugEnabled()) { - log.debug("Valid salt value not found on POST to URL : " + httpReq.getServletPath()); - } - throw new ServletException("Security Violation"); - } + if ("POST".equalsIgnoreCase(httpReq.getMethod())) { + if (SaltValidator.isMultipartFormPost(httpReq) && isStrutsAction(httpReq)) { Review Comment: Edge case: Struts only wraps requests whose full `Content-Type` matches its `MULTIPART_FORM_DATA_REGEX` (boundary ≤ 70 chars, `boundary` before `charset`). A multipart POST this check accepts but Struts doesn't wrap skips validation here and then fails in the interceptor because `getParameter("salt")` is null. Browsers never send those, so probably fine, just noting that deferring on media type alone isn't quite the same decision Struts makes. ########## app/src/test/java/org/apache/roller/weblogger/ui/core/filters/SaltConfigurationTest.java: ########## @@ -0,0 +1,85 @@ +/* + * 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. For additional information regarding + * copyright in this work, please see the NOTICE file in the top level + * directory of this distribution. + */ + +package org.apache.roller.weblogger.ui.core.filters; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class SaltConfigurationTest { + + @Test + public void testSubmittedSaltIsValidatedBeforeResponseSaltIsLoaded() throws Exception { + String webXml = Files.readString(Path.of("src/main/webapp/WEB-INF/web.xml")); Review Comment: cwd-relative, so this passes only when run from `app/`; the other two tests in this class use `getResourceAsStream`, and surefire sets `project.build.directory` for this module. ########## app/src/main/resources/struts.xml: ########## @@ -55,6 +57,7 @@ <!-- <interceptor-ref name="scopedModelDriven"/> --> <!-- <interceptor-ref name="modelDriven"/> --> <interceptor-ref name="fileUpload"/> + <interceptor-ref name="ValidateSaltInterceptor"/> Review Comment: The comment in `ValidateSaltFilter` says multipart params only exist after `fileUpload`, but Struts wraps the request in `MultiPartRequestWrapper` in `StrutsPrepareAndExecuteFilter` before any interceptor runs; `fileUpload` only copies file items into action params. So this ref could sit right after `exception` (validate before anything else does work), and `SaltConfigurationTest:51` shouldn't pin it as adjacent to `fileUpload`. ########## app/src/test/java/org/apache/roller/weblogger/ui/core/filters/SaltConfigurationTest.java: ########## @@ -0,0 +1,85 @@ +/* + * 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. For additional information regarding + * copyright in this work, please see the NOTICE file in the top level + * directory of this distribution. + */ + +package org.apache.roller.weblogger.ui.core.filters; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class SaltConfigurationTest { + + @Test + public void testSubmittedSaltIsValidatedBeforeResponseSaltIsLoaded() throws Exception { + String webXml = Files.readString(Path.of("src/main/webapp/WEB-INF/web.xml")); + + int validateMapping = filterMappingPosition(webXml, "ValidateSaltFilter"); + int loadMapping = filterMappingPosition(webXml, "LoadSaltFilter"); + + assertTrue(validateMapping >= 0, "ValidateSaltFilter mapping is missing"); + assertTrue(loadMapping >= 0, "LoadSaltFilter mapping is missing"); + assertTrue(validateMapping < loadMapping, + "ValidateSaltFilter must run before LoadSaltFilter"); + } + + @Test + public void testMultipartSaltValidationImmediatelyFollowsUploadInterceptor() throws Exception { + String strutsXml = readResource("/struts.xml"); + + Pattern adjacentInterceptors = Pattern.compile( + "<interceptor-ref name=\"fileUpload\"/>\\s*" + + "<interceptor-ref name=\"ValidateSaltInterceptor\"/>"); + + assertTrue(adjacentInterceptors.matcher(strutsXml).find(), + "ValidateSaltInterceptor must immediately follow the upload interceptor"); + } + + @Test + public void testConfigurableSaltBypassIsRemoved() throws Exception { + String properties = readResource( + "/org/apache/roller/weblogger/config/roller.properties"); + + assertFalse(properties.contains("salt.ignored.urls")); Review Comment: Asserting the literal `salt.ignored.urls` is absent from `roller.properties` means a migration note like `# salt.ignored.urls is no longer supported` breaks the build. The behaviour is already covered by the filter no longer reading the property. ########## app/src/test/java/org/apache/roller/weblogger/ui/core/filters/ValidateSaltFilterTest.java: ########## @@ -129,42 +117,117 @@ public void testDoFilterWithPostMethodAndNullRollerSession() throws Exception { when(request.getMethod()).thenReturn("POST"); when(request.getParameter("salt")).thenReturn("validSalt"); when(saltCache.get("validSalt")).thenReturn(""); - StringBuffer requestURL = new StringBuffer("https://example.com/app/ignoredurl"); - when(request.getRequestURL()).thenReturn(requestURL); - filter.doFilter(request, response, chain); verify(saltCache, never()).remove("validSalt"); } } @Test - public void testDoFilterWithIgnoredURL() throws Exception { + public void testPostWithoutParameterRejectsRequestAttributeSalt() throws Exception { try (MockedStatic<RollerSession> mockedRollerSession = mockStatic(RollerSession.class); - MockedStatic<SaltCache> mockedSaltCache = mockStatic(SaltCache.class); - MockedStatic<WebloggerConfig> mockedWebloggerConfig = mockStatic(WebloggerConfig.class)) { + MockedStatic<SaltCache> mockedSaltCache = mockStatic(SaltCache.class)) { mockedRollerSession.when(() -> RollerSession.getRollerSession(request)).thenReturn(rollerSession); mockedSaltCache.when(SaltCache::getInstance).thenReturn(saltCache); - mockedWebloggerConfig.when(() -> WebloggerConfig.getProperty("salt.ignored.urls")) - .thenReturn("https://example.com/app/ignoredurl?param1=value1&m2=value2"); when(request.getMethod()).thenReturn("POST"); - StringBuffer requestURL = new StringBuffer("https://example.com/app/ignoredurl"); - when(request.getRequestURL()).thenReturn(requestURL); - when(request.getQueryString()).thenReturn("param1=value1&m2=value2"); - when(request.getParameter("salt")).thenReturn(null); // No salt provided + when(request.getAttribute("salt")).thenReturn("responseSalt"); + when(request.getParameter("salt")).thenReturn(null); + when(rollerSession.getAuthenticatedUser()).thenReturn(new TestUser("userId")); + when(saltCache.get("responseSalt")).thenReturn("userId"); - filter.init(mock(FilterConfig.class)); - filter.doFilter(request, response, chain); + assertThrows(ServletException.class, + () -> filter.doFilter(request, response, chain)); - verify(chain).doFilter(request, response); + verify(chain, never()).doFilter(request, response); verify(saltCache, never()).get(anyString()); verify(saltCache, never()).remove(anyString()); } } + @Test + public void testSubmittedSaltCanOnlyBeUsedOnce() throws Exception { + try (MockedStatic<RollerSession> mockedRollerSession = mockStatic(RollerSession.class); + MockedStatic<SaltCache> mockedSaltCache = mockStatic(SaltCache.class)) { + + mockedRollerSession.when(() -> RollerSession.getRollerSession(request)).thenReturn(rollerSession); + mockedSaltCache.when(SaltCache::getInstance).thenReturn(saltCache); + + when(request.getMethod()).thenReturn("POST"); + when(request.getParameter("salt")).thenReturn("validSalt"); + when(rollerSession.getAuthenticatedUser()).thenReturn(new TestUser("userId")); + when(saltCache.get("validSalt")).thenReturn("userId", (String) null); + + filter.doFilter(request, response, chain); + assertThrows(ServletException.class, + () -> filter.doFilter(request, response, chain)); + + verify(chain, times(1)).doFilter(request, response); + verify(saltCache, times(1)).remove("validSalt"); + } + } + + @Test + public void testMultipartStrutsPostIsDeferred() throws Exception { + when(request.getMethod()).thenReturn("POST"); + when(request.getContentType()).thenReturn("multipart/form-data; boundary=abc123"); + when(request.getServletPath()).thenReturn("/roller-ui/mediaFileAdd!save.rol"); + + filter.doFilter(request, response, chain); + + verify(chain).doFilter(request, response); + verify(request, never()).getParameter("salt"); + } + + @Test + public void testMultipartNonStrutsPostIsNotDeferred() throws Exception { + try (MockedStatic<RollerSession> mockedRollerSession = mockStatic(RollerSession.class)) { + mockedRollerSession.when(() -> RollerSession.getRollerSession(request)).thenReturn(rollerSession); + + when(request.getMethod()).thenReturn("POST"); + when(request.getContentType()).thenReturn("multipart/form-data; boundary=abc123"); + when(request.getServletPath()).thenReturn("/roller-ui/upload"); + when(request.getParameter("salt")).thenReturn(null); + + assertThrows(ServletException.class, + () -> filter.doFilter(request, response, chain)); + + verify(chain, never()).doFilter(request, response); + } + } + + @Test + public void testValidationRunsBeforeResponseSaltGeneration() throws Exception { Review Comment: This builds the chain in validate-then-load order and then asserts that order, so it can't fail if `web.xml` is swapped back; `SaltConfigurationTest` already covers the ordering. ########## app/src/main/java/org/apache/roller/weblogger/ui/core/filters/ValidateSaltFilter.java: ########## @@ -31,53 +28,35 @@ import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; -import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.roller.weblogger.config.WebloggerConfig; -import org.apache.roller.weblogger.ui.rendering.util.cache.SaltCache; -import org.apache.roller.weblogger.ui.core.RollerSession; /** * Filter checks all POST request for presence of valid salt value and rejects those without * a salt value or with a salt value not generated by this Roller instance. */ public class ValidateSaltFilter implements Filter { private static final Log log = LogFactory.getLog(ValidateSaltFilter.class); - private Set<String> ignored = Collections.emptySet(); @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpReq = (HttpServletRequest) request; - String requestURL = httpReq.getRequestURL().toString(); - String queryString = httpReq.getQueryString(); - if (queryString != null) { - requestURL += "?" + queryString; - } - - if ("POST".equals(httpReq.getMethod()) && !isIgnoredURL(requestURL)) { - RollerSession rollerSession = RollerSession.getRollerSession(httpReq); - if (rollerSession != null) { - String userId = rollerSession.getAuthenticatedUser() != null ? rollerSession.getAuthenticatedUser().getId() : ""; - - Object saltObject = httpReq.getAttribute("salt"); // multi-form post case - String salt = saltObject != null ? saltObject.toString() : null; - salt = salt != null ? salt : httpReq.getParameter("salt"); - SaltCache saltCache = SaltCache.getInstance(); - if (salt == null || !Objects.equals(saltCache.get(salt), userId)) { - if (log.isDebugEnabled()) { - log.debug("Valid salt value not found on POST to URL : " + httpReq.getServletPath()); - } - throw new ServletException("Security Violation"); - } + if ("POST".equalsIgnoreCase(httpReq.getMethod())) { + if (SaltValidator.isMultipartFormPost(httpReq) && isStrutsAction(httpReq)) { + // Struts makes multipart parameters available after its upload + // interceptor; ValidateSaltInterceptor handles these requests. + chain.doFilter(request, response); + return; + } - // Remove salt from cache after successful validation - saltCache.remove(salt); + if (!SaltValidator.consumeSubmittedSalt(httpReq)) { if (log.isDebugEnabled()) { - log.debug("Salt used and invalidated: " + salt); + log.debug("Valid salt value not found on POST to URL : " + + httpReq.getServletPath()); } + throw new ServletException("Security Violation"); Review Comment: Nit: this block is duplicated in the interceptor; a `SaltValidator.requireSubmittedSalt(request)` that throws would keep both rejection paths in sync. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
