From 97851146f09f55ef6259180ec6b4e366063e7d9f Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Mon, 16 Nov 2026 22:04:10 -0700 Subject: [PATCH 01/25] Don't match the external-login placeholder as a password Users who log in through LDAP or the servlet container have users.passwords.externalAuthValue stored in place of a Roller password. Roller's password encoder no longer matches that placeholder, so it isn't treated as a password anywhere the encoder checks one. --- .../weblogger/ui/core/RollerContext.java | 5 +- .../ExternalLoginAwarePasswordEncoder.java | 54 +++++++++++++++++ ...ExternalLoginAwarePasswordEncoderTest.java | 59 +++++++++++++++++++ 3 files changed, 116 insertions(+), 2 deletions(-) create mode 100644 app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java create mode 100644 app/src/test/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoderTest.java diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerContext.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerContext.java index 0955747bc9..7fee33870e 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerContext.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerContext.java @@ -44,6 +44,7 @@ import org.apache.roller.weblogger.business.startup.WebloggerStartup; import org.apache.roller.weblogger.ui.core.plugins.UIPluginManager; import org.apache.roller.weblogger.ui.core.plugins.UIPluginManagerImpl; +import org.apache.roller.weblogger.ui.core.security.ExternalLoginAwarePasswordEncoder; import org.apache.roller.weblogger.ui.core.security.AutoProvision; import org.apache.roller.weblogger.ui.core.security.BootstrapSecurity; import org.apache.roller.weblogger.util.Reflection; @@ -70,7 +71,7 @@ public class RollerContext extends ContextLoaderListener private static final Log log = LogFactory.getLog(RollerContext.class); private static ServletContext servletContext = null; - private static DelegatingPasswordEncoder encoder; + private static PasswordEncoder encoder; public RollerContext() { @@ -278,7 +279,7 @@ protected void initializeSecurityFeatures(ServletContext context) { } } - encoder = createPasswordEncoder(); + encoder = new ExternalLoginAwarePasswordEncoder(createPasswordEncoder()); String daoBeanName = "org.springframework.security.authentication.dao.DaoAuthenticationProvider#0"; diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java new file mode 100644 index 0000000000..afe5949bd0 --- /dev/null +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java @@ -0,0 +1,54 @@ +/* + * 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.core.security; + +import org.apache.roller.weblogger.config.WebloggerConfig; +import org.springframework.security.crypto.password.PasswordEncoder; + +/** + * Users who log in through LDAP or the servlet container have no Roller + * password; Roller stores users.passwords.externalAuthValue in its place. + * That placeholder is not a password, so this encoder never matches it. + */ +public class ExternalLoginAwarePasswordEncoder implements PasswordEncoder { + + private final PasswordEncoder delegate; + + public ExternalLoginAwarePasswordEncoder(PasswordEncoder delegate) { + this.delegate = delegate; + } + + @Override + public String encode(CharSequence rawPassword) { + return delegate.encode(rawPassword); + } + + @Override + public boolean matches(CharSequence rawPassword, String encodedPassword) { + String marker = WebloggerConfig.getProperty("users.passwords.externalAuthValue", ""); + if (rawPassword != null && marker != null && !marker.isEmpty() && marker.contentEquals(rawPassword)) { + return false; + } + return delegate.matches(rawPassword, encodedPassword); + } + + @Override + public boolean upgradeEncoding(String encodedPassword) { + return delegate.upgradeEncoding(encodedPassword); + } +} diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoderTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoderTest.java new file mode 100644 index 0000000000..8bad9ab639 --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoderTest.java @@ -0,0 +1,59 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.roller.weblogger.ui.core.security; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.DelegatingPasswordEncoder; +import org.springframework.security.crypto.password.NoOpPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ExternalLoginAwarePasswordEncoderTest { + + @SuppressWarnings("deprecation") + private static PasswordEncoder encoder() { + Map encoders = new HashMap<>(); + // as with passwds.encryption.lazyUpgradeFrom=plaintext + encoders.put(null, NoOpPasswordEncoder.getInstance()); + encoders.put("bcrypt", new BCryptPasswordEncoder()); + return new ExternalLoginAwarePasswordEncoder(new DelegatingPasswordEncoder("bcrypt", encoders)); + } + + @Test + void thePlaceholderIsNotAPassword() { + PasswordEncoder encoder = encoder(); + // as Register stores it for container-managed and LDAP sign-ups + assertFalse(encoder.matches("", encoder.encode(""))); + // as CustomUserRegistry stores it for directory users + assertFalse(encoder.matches("", "")); + } + + @Test + void otherPasswordsStillWork() { + PasswordEncoder encoder = encoder(); + assertTrue(encoder.matches("secret", encoder.encode("secret"))); + assertTrue(encoder.matches("old-plain", "old-plain")); + assertFalse(encoder.matches("wrong", encoder.encode("secret"))); + } +} From f3cb29a8fd89661338250544d90c8bb5983b1f73 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Tue, 17 Nov 2026 16:34:31 -0700 Subject: [PATCH 02/25] End a user's other sessions when their password changes or their account is disabled RollerSession now keeps a SHA-256 digest of the user's stored password hash from when the session logged in. On each lookup it reloads the user and, if the user is gone, disabled, or has a different password hash, it invalidates the HTTP session, clears the Spring SecurityContext for the request, and continues with an empty session, so the browser has to log in again. The check runs before the session-cache check, which would otherwise rebuild the session from the existing login. It applies to form, remember-me and OpenID logins alike, since the session tracks the Roller user name rather than the principal. Profile.save and UserEdit.save (when an administrator edits their own account) refresh the digest of the session that made the change, so that session stays logged in. Both actions now receive the servlet request through ServletRequestAware, as Register already does. (cherry picked from commit 32d476caae0712ad12cbe99c3f5e2901e8c9cae5) --- .../weblogger/ui/core/RollerSession.java | 94 ++++- .../weblogger/ui/struts2/admin/UserEdit.java | 23 +- .../weblogger/ui/struts2/core/Profile.java | 19 +- .../ui/core/PasswordChangeSessionTest.java | 327 ++++++++++++++++++ 4 files changed, 459 insertions(+), 4 deletions(-) create mode 100644 app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java index a1b1caf33a..0bb6a42e75 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java @@ -19,6 +19,9 @@ package org.apache.roller.weblogger.ui.core; import java.io.Serializable; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.security.Principal; import javax.servlet.http.HttpServletRequest; @@ -35,6 +38,7 @@ import org.apache.roller.weblogger.pojos.User; import org.apache.roller.weblogger.ui.core.security.AutoProvision; import org.apache.roller.weblogger.ui.core.security.OpenIdUrls; +import org.springframework.security.core.context.SecurityContextHolder; /** @@ -47,6 +51,9 @@ public class RollerSession // the id of the user represented by this session private String userName = null; + + // digest of the user's stored password hash when this session logged in + private String passwordDigest = null; private static final Log log; @@ -70,10 +77,18 @@ public static RollerSession getRollerSession(HttpServletRequest request) { // Create new session if none exists rollerSession = new RollerSession(); session.setAttribute(ROLLER_SESSION, rollerSession); - } else if (rollerSession.getAuthenticatedUser() != null) { + } else if (rollerSession.userName != null) { + // A session that logged in ends once the user's password has + // changed or the user was disabled or removed, so changing a + // password also logs out the user's other browsers. This runs + // before the cache check below, which rebuilds the session + // from the login and would take on the new password. + if (!rollerSession.isCurrent()) { + return endSession(request, session); + } // Check if session is still valid in cache RollerLoginSessionManager manager = RollerLoginSessionManager.getInstance(); - String username = rollerSession.getAuthenticatedUser().getUserName(); + String username = rollerSession.userName; if (manager.get(username) == null) { rollerSession = new RollerSession(); session.setAttribute(ROLLER_SESSION, rollerSession); @@ -124,6 +139,80 @@ public static RollerSession getRollerSession(HttpServletRequest request) { return rollerSession; } + /** + * Keeps the current session logged in after its own user changed their + * password, or an administrator changed their own. Call it after the new + * password is saved; the user's other sessions still end. + */ + public static void refreshPassword(HttpServletRequest request, User user) { + HttpSession session = request != null ? request.getSession(false) : null; + if (session == null || user == null) { + return; + } + Object attribute = session.getAttribute(ROLLER_SESSION); + if (attribute instanceof RollerSession + && user.getUserName().equals(((RollerSession) attribute).userName)) { + ((RollerSession) attribute).setAuthenticatedUser(user); + } + } + + /** + * Whether the user this session logged in as is still enabled and still + * has the password the session logged in with. A failed lookup keeps the + * session, so a database error does not log everyone out. + */ + private boolean isCurrent() { + User user; + try { + UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); + // only finds enabled users + user = mgr.getUserByUserName(userName); + } catch (WebloggerException ex) { + log.warn("Error looking up authenticated user " + userName, ex); + return true; + } + return user != null && digest(user).equals(passwordDigest); + } + + /** + * Ends a session whose login no longer holds: invalidates it, clears the + * login from this request, and gives the rest of the request a new + * session with no user, as any visitor who is not logged in gets. + */ + private static RollerSession endSession(HttpServletRequest request, HttpSession session) { + log.info("Ending session of a user whose password or account changed"); + try { + session.invalidate(); + } catch (IllegalStateException ignored) { + // already invalidated + } + SecurityContextHolder.clearContext(); + RollerSession rollerSession = new RollerSession(); + try { + request.getSession(true).setAttribute(ROLLER_SESSION, rollerSession); + } catch (IllegalStateException e) { + // response already committed, the next request gets a new session + log.debug("Could not start a new session", e); + } + return rollerSession; + } + + /** Digest of the stored password hash, so the session does not hold it. */ + private static String digest(User user) { + String password = user.getPassword() != null ? user.getPassword() : ""; + try { + MessageDigest sha = MessageDigest.getInstance("SHA-256"); + byte[] hash = sha.digest(password.getBytes(StandardCharsets.UTF_8)); + StringBuilder hex = new StringBuilder(hash.length * 2); + for (byte b : hash) { + hex.append(String.format("%02x", b)); + } + return hex.toString(); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 is required by the Java spec", e); + } + } + /** Create session's Roller instance */ @Override public void sessionCreated(HttpSessionEvent se) { @@ -171,6 +260,7 @@ public User getAuthenticatedUser() { */ public void setAuthenticatedUser(User authenticatedUser) { this.userName = authenticatedUser.getUserName(); + this.passwordDigest = digest(authenticatedUser); RollerLoginSessionManager sessionManager = RollerLoginSessionManager.getInstance(); sessionManager.register(authenticatedUser.getUserName(), this); } diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/admin/UserEdit.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/admin/UserEdit.java index 70878ecf82..cfd138146c 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/admin/UserEdit.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/admin/UserEdit.java @@ -24,6 +24,8 @@ import java.util.Locale; import java.util.TimeZone; +import javax.servlet.http.HttpServletRequest; + import org.apache.commons.lang3.CharSetUtils; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; @@ -38,8 +40,10 @@ import org.apache.roller.weblogger.pojos.User; import org.apache.roller.weblogger.pojos.WeblogPermission; import org.apache.roller.weblogger.ui.core.RollerLoginSessionManager; +import org.apache.roller.weblogger.ui.core.RollerSession; import org.apache.roller.weblogger.ui.struts2.core.Register; import org.apache.roller.weblogger.ui.struts2.util.UIAction; +import org.apache.struts2.interceptor.ServletRequestAware; import org.apache.struts2.interceptor.validation.SkipValidation; @@ -47,13 +51,15 @@ * Action that allows an admin to modify a users profile. */ // TODO: make this work @AllowedMethods({"execute","save","firstSave"}) -public class UserEdit extends UIAction { +public class UserEdit extends UIAction implements ServletRequestAware { private static Log log = LogFactory.getLog(UserEdit.class); // a bean to store our form data private CreateUserBean bean = new CreateUserBean(); + private HttpServletRequest servletRequest = null; + // user we are creating or modifying private User user = null; @@ -212,6 +218,12 @@ public String save() { } WebloggerFactory.getWeblogger().flush(); + // a password change ends the user's sessions, except this one + // when the administrator edits their own account + if (!isAdd() && isUserEditingSelf()) { + RollerSession.refreshPassword(getServletRequest(), user); + } + // successful add or edit: send user back to user admin page bean = new CreateUserBean(); addMessage("userAdmin.userSaved"); @@ -272,6 +284,15 @@ private void myValidate() { } } + protected HttpServletRequest getServletRequest() { + return servletRequest; + } + + @Override + public void setServletRequest(HttpServletRequest servletRequest) { + this.servletRequest = servletRequest; + } + public CreateUserBean getBean() { return bean; } diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Profile.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Profile.java index 6f83a0ddb6..6f31897c27 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Profile.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Profile.java @@ -27,7 +27,9 @@ import org.apache.roller.weblogger.config.AuthMethod; import org.apache.roller.weblogger.config.WebloggerConfig; import org.apache.roller.weblogger.pojos.User; +import org.apache.roller.weblogger.ui.core.RollerSession; import org.apache.roller.weblogger.ui.struts2.util.UIAction; +import org.apache.struts2.interceptor.ServletRequestAware; import org.apache.struts2.interceptor.validation.SkipValidation; import java.util.Arrays; @@ -35,14 +37,18 @@ import java.util.Optional; import java.util.TimeZone; +import javax.servlet.http.HttpServletRequest; + /** * Allows user to edit his/her profile. */ // TODO: make this work @AllowedMethods({"execute","save"}) -public class Profile extends UIAction { +public class Profile extends UIAction implements ServletRequestAware { private static Log log = LogFactory.getLog(Profile.class); private ProfileBean bean = new ProfileBean(); + + private HttpServletRequest servletRequest = null; private AuthMethod authMethod = WebloggerConfig.getAuthMethod(); public Profile() { @@ -122,6 +128,8 @@ public String save() { UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); mgr.saveUser(existingUser); WebloggerFactory.getWeblogger().flush(); + // a password change ends the user's other sessions, not this one + RollerSession.refreshPassword(getServletRequest(), existingUser); addMessage("generic.changes.saved"); return SUCCESS; } catch (WebloggerException ex) { @@ -176,6 +184,15 @@ public void myValidate() { } } + protected HttpServletRequest getServletRequest() { + return servletRequest; + } + + @Override + public void setServletRequest(HttpServletRequest servletRequest) { + this.servletRequest = servletRequest; + } + public String getAuthMethod() { return authMethod.name(); } diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java new file mode 100644 index 0000000000..327ab4d8d7 --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java @@ -0,0 +1,327 @@ +/* + * 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.core; + +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import org.apache.roller.weblogger.TestUtils; +import org.apache.roller.weblogger.business.UserManager; +import org.apache.roller.weblogger.business.WebloggerFactory; +import org.apache.roller.weblogger.pojos.User; +import org.apache.roller.weblogger.ui.struts2.admin.CreateUserBean; +import org.apache.roller.weblogger.ui.struts2.admin.UserEdit; +import org.apache.roller.weblogger.ui.struts2.core.Profile; +import org.apache.roller.weblogger.ui.struts2.core.ProfileBean; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.DelegatingPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +/** + * A user logged in from two browsers changes their password in one of them, or + * an administrator resets or disables the account. The other browser's session + * ends on its next request, and the session that made the change stays logged + * in. + */ +class PasswordChangeSessionTest { + + private String userName; + private String adminName; + private PasswordEncoder savedEncoder; + + @BeforeEach + void setUp() throws Exception { + TestUtils.setupWeblogger(); + savedEncoder = swapEncoder(new DelegatingPasswordEncoder("bcrypt", + Map.of("bcrypt", new BCryptPasswordEncoder(4)))); + userName = TestUtils.setupUser("sessionuser").getUserName(); + adminName = TestUtils.setupUser("sessionadmin").getUserName(); + TestUtils.endSession(true); + } + + @AfterEach + void tearDown() throws Exception { + SecurityContextHolder.clearContext(); + TestUtils.teardownUser(userName); + TestUtils.teardownUser(adminName); + TestUtils.endSession(true); + swapEncoder(savedEncoder); + } + + @Test + void changingOwnPasswordEndsTheUsersOtherSessions() throws Exception { + Browser a = new Browser(userName); + Browser b = new Browser(userName); + assertEquals(userName, a.request().getAuthenticatedUser().getUserName()); + assertEquals(userName, b.request().getAuthenticatedUser().getUserName()); + TestUtils.endSession(true); + + a.request(); + Profile profile = spy(new Profile()); + stubText(profile); + User self = user(userName); + ProfileBean bean = new ProfileBean(); + bean.copyFrom(self); + bean.setPasswordText("changed-password"); + bean.setPasswordConfirm("changed-password"); + profile.setBean(bean); + profile.setAuthenticatedUser(self); + profile.setServletRequest(a.httpRequest); + assertEquals(Profile.SUCCESS, profile.save()); + TestUtils.endSession(true); + + b.assertLoggedOut(); + a.assertLoggedIn(userName); + } + + @Test + void adminPasswordResetEndsTheUsersSessions() throws Exception { + Browser admin = new Browser(adminName); + Browser b = new Browser(userName); + admin.request(); + assertEquals(userName, b.request().getAuthenticatedUser().getUserName()); + TestUtils.endSession(true); + + saveAsAdmin(admin, bean -> bean.setPassword("reset-password")); + + b.assertLoggedOut(); + admin.assertLoggedIn(adminName); + } + + @Test + void disablingAUserEndsTheirSessions() throws Exception { + Browser admin = new Browser(adminName); + Browser b = new Browser(userName); + admin.request(); + assertEquals(userName, b.request().getAuthenticatedUser().getUserName()); + TestUtils.endSession(true); + + saveAsAdmin(admin, bean -> bean.setEnabled(false)); + + b.assertLoggedOut(); + admin.assertLoggedIn(adminName); + } + + @Test + void disablingAUserEndsTheirOpenIdSessions() throws Exception { + // OpenID 2.0 logins carry the user's OpenID URL as the principal name + String openIdUrl = "https://openid.example.com/sessionuser"; + UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); + User u = user(userName); + u.setOpenIdUrl(openIdUrl); + mgr.saveUser(u); + TestUtils.endSession(true); + + Browser admin = new Browser(adminName); + Browser b = new Browser(openIdUrl + "/"); + admin.request(); + assertEquals(userName, b.request().getAuthenticatedUser().getUserName()); + TestUtils.endSession(true); + + saveAsAdmin(admin, bean -> bean.setEnabled(false)); + + b.assertLoggedOut(); + admin.assertLoggedIn(adminName); + } + + @Test + void adminChangingOwnPasswordStaysLoggedIn() throws Exception { + Browser admin = new Browser(adminName); + Browser other = new Browser(adminName); + admin.request(); + other.request(); + TestUtils.endSession(true); + + admin.request(); + UserEdit action = userEdit(admin, adminName); + action.getBean().setPassword("reset-password"); + assertEquals(UserEdit.SUCCESS, action.save()); + TestUtils.endSession(true); + + other.assertLoggedOut(); + admin.assertLoggedIn(adminName); + } + + @Test + void savingWithoutAPasswordChangeKeepsOtherSessions() throws Exception { + Browser admin = new Browser(adminName); + Browser b = new Browser(userName); + admin.request(); + b.request(); + TestUtils.endSession(true); + + saveAsAdmin(admin, bean -> bean.setFullName("Renamed User")); + + b.assertLoggedIn(userName); + } + + private void saveAsAdmin(Browser admin, java.util.function.Consumer change) + throws Exception { + admin.request(); + UserEdit action = userEdit(admin, userName); + change.accept(action.getBean()); + assertEquals(UserEdit.SUCCESS, action.save()); + TestUtils.endSession(true); + } + + private UserEdit userEdit(Browser admin, String target) throws Exception { + UserEdit action = spy(new UserEdit()); + stubText(action); + action.setActionName("modifyUser"); + action.setAuthenticatedUser(user(adminName)); + action.setServletRequest(admin.httpRequest); + action.getBean().setId(user(target).getId()); + action.myPrepare(); + action.getBean().copyFrom(user(target)); + action.getBean().setPassword(null); + return action; + } + + private static void stubText(org.apache.roller.weblogger.ui.struts2.util.UIAction action) { + doAnswer(call -> call.getArgument(0)).when(action).getText(anyString()); + doAnswer(call -> call.getArgument(0)).when(action).getText(anyString(), anyString()); + doAnswer(call -> call.getArgument(0)).when(action).getText(anyString(), anyList()); + } + + private static User user(String name) throws Exception { + UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); + return mgr.getUserByUserName(name, null); + } + + private static PasswordEncoder swapEncoder(PasswordEncoder encoder) throws Exception { + Field field = RollerContext.class.getDeclaredField("encoder"); + field.setAccessible(true); + PasswordEncoder previous = (PasswordEncoder) field.get(null); + field.set(null, encoder); + return previous; + } + + /** + * One browser: an HTTP session and the Spring login stored in it. Each + * request puts that login in the SecurityContextHolder, as Spring does, + * while the session holding it is still valid. + */ + private static final class Browser { + final HttpServletRequest httpRequest = mock(HttpServletRequest.class); + final Authentication login; + HttpSession session; + // the session holding the login was invalidated + boolean ended; + + Browser(String name) { + login = UsernamePasswordAuthenticationToken.authenticated(name, null, List.of()); + session = newSession(); + // keep reporting the original login, so a rebuild from it would show + when(httpRequest.getUserPrincipal()).thenReturn(login); + when(httpRequest.getSession(false)).thenAnswer(call -> session); + when(httpRequest.getSession(true)).thenAnswer(call -> { + if (session == null) { + session = newSession(); + } + return session; + }); + when(httpRequest.getSession()).thenAnswer(call -> httpRequest.getSession(true)); + } + + private HttpSession newSession() { + Map attributes = new HashMap<>(); + boolean[] valid = {true}; + HttpSession s = mock(HttpSession.class); + when(s.getAttribute(anyString())).thenAnswer(call -> { + checkValid(valid); + return attributes.get(call.getArgument(0)); + }); + doAnswer(call -> { + checkValid(valid); + attributes.put(call.getArgument(0), call.getArgument(1)); + return null; + }).when(s).setAttribute(anyString(), any()); + doAnswer(call -> { + checkValid(valid); + valid[0] = false; + attributes.clear(); + ended = true; + if (session == s) { + session = null; + } + return null; + }).when(s).invalidate(); + return s; + } + + private static void checkValid(boolean[] valid) { + if (!valid[0]) { + throw new IllegalStateException("session invalidated"); + } + } + + RollerSession request() { + if (ended) { + SecurityContextHolder.clearContext(); + } else { + SecurityContextHolder.getContext().setAuthentication(login); + } + return RollerSession.getRollerSession(httpRequest); + } + + void assertLoggedOut() { + RollerSession rollerSession = request(); + assertNull(rollerSession == null ? null : rollerSession.getAuthenticatedUser(), + "the session should no longer have a user"); + assertTrue(ended, "the HTTP session should be invalidated"); + assertNull(SecurityContextHolder.getContext().getAuthentication(), + "the login should be cleared from this request"); + SecurityContextHolder.clearContext(); + } + + void assertLoggedIn(String name) { + RollerSession rollerSession = request(); + assertNotNull(rollerSession); + assertNotNull(rollerSession.getAuthenticatedUser(), "the session should keep its user"); + assertEquals(name, rollerSession.getAuthenticatedUser().getUserName()); + assertFalse(ended, "the HTTP session should stay valid"); + assertNotNull(SecurityContextHolder.getContext().getAuthentication()); + SecurityContextHolder.clearContext(); + } + } +} From b250c368fa093eb93161a00bb6a4f34631b3ca27 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Tue, 17 Nov 2026 19:47:54 -0700 Subject: [PATCH 03/25] Keep the stored password when an OpenID account's profile is saved without a sign-in change Profile.save and UserEdit.save generated a new random stored password for OpenID accounts on every save, so with the session check a profile-only edit ended the user's other sessions. They now generate one only when the account has no stored password or its OpenID URL changes. PasswordChangeSessionTest covers a profile edit and an administrator edit of an OpenID account with another session open, and switching an account to OpenID. --- .../weblogger/ui/struts2/admin/UserEdit.java | 11 ++- .../weblogger/ui/struts2/core/Profile.java | 11 ++- .../ui/core/PasswordChangeSessionTest.java | 99 +++++++++++++++++++ 3 files changed, 115 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/admin/UserEdit.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/admin/UserEdit.java index cfd138146c..5559fccbac 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/admin/UserEdit.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/admin/UserEdit.java @@ -147,6 +147,7 @@ public String save() { myValidate(); if (!hasActionErrors()) { + String previousOpenIdUrl = user.getOpenIdUrl(); getBean().copyTo(user); if (authMethod == AuthMethod.DB_OPENID) { @@ -162,9 +163,13 @@ public String save() { } } - // User.password does not allow null, so generate one - if (authMethod.equals(AuthMethod.OPENID) || - (authMethod.equals(AuthMethod.DB_OPENID) && !StringUtils.isEmpty(bean.getOpenIdUrl()))) { + // User.password does not allow null, so generate one when the user + // starts signing in with an OpenID URL. Keep the stored one when the + // OpenID URL is unchanged, so an edit doesn't end the user's sessions. + if ((authMethod.equals(AuthMethod.OPENID) || + (authMethod.equals(AuthMethod.DB_OPENID) && !StringUtils.isEmpty(bean.getOpenIdUrl()))) + && (StringUtils.isEmpty(user.getPassword()) + || !StringUtils.equals(previousOpenIdUrl, user.getOpenIdUrl()))) { String randomString = RandomStringUtils.randomAlphanumeric(255); user.resetPassword(randomString); } diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Profile.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Profile.java index 6f31897c27..64a7d26dc2 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Profile.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Profile.java @@ -79,6 +79,7 @@ public String save() { // We ONLY modify the user currently logged in User existingUser = getAuthenticatedUser(); + String previousOpenIdUrl = existingUser.getOpenIdUrl(); // copy updated attributes getBean().copyTo(existingUser); @@ -110,9 +111,13 @@ public String save() { } } - // User.password does not allow null, so generate one - if (authMethod.equals(AuthMethod.OPENID) || - (authMethod.equals(AuthMethod.DB_OPENID) && !StringUtils.isEmpty(bean.getOpenIdUrl()))) { + // User.password does not allow null, so generate one when the user + // starts signing in with an OpenID URL. Keep the stored one when the + // OpenID URL is unchanged, so an edit doesn't end the user's sessions. + if ((authMethod.equals(AuthMethod.OPENID) || + (authMethod.equals(AuthMethod.DB_OPENID) && !StringUtils.isEmpty(bean.getOpenIdUrl()))) + && (StringUtils.isEmpty(existingUser.getPassword()) + || !StringUtils.equals(previousOpenIdUrl, existingUser.getOpenIdUrl()))) { String randomString = RandomStringUtils.randomAlphanumeric(255); existingUser.resetPassword(randomString); } diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java index 327ab4d8d7..51be1eaa70 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java @@ -29,6 +29,7 @@ import org.apache.roller.weblogger.TestUtils; import org.apache.roller.weblogger.business.UserManager; import org.apache.roller.weblogger.business.WebloggerFactory; +import org.apache.roller.weblogger.config.AuthMethod; import org.apache.roller.weblogger.pojos.User; import org.apache.roller.weblogger.ui.struts2.admin.CreateUserBean; import org.apache.roller.weblogger.ui.struts2.admin.UserEdit; @@ -46,6 +47,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -195,6 +197,103 @@ void savingWithoutAPasswordChangeKeepsOtherSessions() throws Exception { b.assertLoggedIn(userName); } + @Test + void openIdProfileEditKeepsTheUsersOtherSessions() throws Exception { + linkOpenId(userName, "https://openid.example.com/sessionuser"); + Browser a = new Browser(userName); + Browser b = new Browser(userName); + a.request(); + b.request(); + TestUtils.endSession(true); + String storedPassword = user(userName).getPassword(); + + a.request(); + Profile profile = spy(new Profile()); + stubText(profile); + setAuthMethod(profile, AuthMethod.OPENID); + User self = user(userName); + ProfileBean bean = new ProfileBean(); + bean.copyFrom(self); + bean.setScreenName("Renamed"); + profile.setBean(bean); + profile.setAuthenticatedUser(self); + profile.setServletRequest(a.httpRequest); + assertEquals(Profile.SUCCESS, profile.save(), () -> String.valueOf(profile.getActionErrors())); + TestUtils.endSession(true); + + assertEquals("Renamed", user(userName).getScreenName()); + assertEquals(storedPassword, user(userName).getPassword()); + b.assertLoggedIn(userName); + a.assertLoggedIn(userName); + } + + @Test + void adminEditOfAnOpenIdUserKeepsTheirSessions() throws Exception { + linkOpenId(userName, "https://openid.example.com/sessionuser"); + Browser admin = new Browser(adminName); + Browser b = new Browser(userName); + admin.request(); + b.request(); + TestUtils.endSession(true); + String storedPassword = user(userName).getPassword(); + + admin.request(); + UserEdit action = userEdit(admin, userName); + setAuthMethod(action, AuthMethod.DB_OPENID); + action.getBean().setFullName("Renamed User"); + assertEquals(UserEdit.SUCCESS, action.save(), () -> String.valueOf(action.getActionErrors())); + TestUtils.endSession(true); + + assertEquals(storedPassword, user(userName).getPassword()); + b.assertLoggedIn(userName); + } + + @Test + void switchingToOpenIdReplacesTheStoredPassword() throws Exception { + Browser admin = new Browser(adminName); + Browser b = new Browser(userName); + admin.request(); + b.request(); + TestUtils.endSession(true); + String storedPassword = user(userName).getPassword(); + + admin.request(); + UserEdit action = userEdit(admin, userName); + setAuthMethod(action, AuthMethod.DB_OPENID); + action.getBean().setOpenIdUrl("https://openid.example.com/sessionuser"); + assertEquals(UserEdit.SUCCESS, action.save(), () -> String.valueOf(action.getActionErrors())); + TestUtils.endSession(true); + + assertNotEquals(storedPassword, user(userName).getPassword()); + b.assertLoggedOut(); + } + + private static void linkOpenId(String name, String openIdUrl) throws Exception { + UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); + User u = mgr.getUserByUserName(name, null); + u.setOpenIdUrl(openIdUrl); + mgr.saveUser(u); + TestUtils.endSession(true); + } + + private static void setAuthMethod(Object action, AuthMethod method) throws Exception { + // the action is a Mockito spy, a subclass of the real action + Field field = findField(action.getClass(), "authMethod"); + field.setAccessible(true); + field.set(action, method); + } + + private static Field findField(Class type, String name) throws NoSuchFieldException { + for (Class c = type; c != null; c = c.getSuperclass()) { + try { + return c.getDeclaredField(name); + } catch (NoSuchFieldException ignored) { + // keep looking in the superclass + } + } + throw new NoSuchFieldException(name); + } + private void saveAsAdmin(Browser admin, java.util.function.Consumer change) throws Exception { admin.request(); From f59b841a2f454df1edee8ab12a5eaf31af8b4cc9 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Tue, 17 Nov 2026 19:52:19 -0700 Subject: [PATCH 04/25] Reject the external-login placeholder as a chosen password and never match an empty one Registration, the profile page and the admin user editor now reject users.passwords.externalAuthValue, and the default , as a new password with a validation message, since that value never matches at login. An account that already has it can be given a new password by an administrator. An empty configured value now falls back to for what Roller stores, and the password encoder never matches an empty password or the default placeholder. --- .../ui/core/security/CustomUserRegistry.java | 2 +- .../ExternalLoginAwarePasswordEncoder.java | 30 ++- .../weblogger/ui/struts2/admin/UserEdit.java | 5 + .../weblogger/ui/struts2/core/Profile.java | 5 + .../weblogger/ui/struts2/core/Register.java | 9 +- .../resources/ApplicationResources.properties | 1 + .../ui/core/ExternalLoginPlaceholderTest.java | 208 ++++++++++++++++++ .../core/ExternalLoginMarkerPasswordTest.java | 203 +++++++++++++++++ 8 files changed, 458 insertions(+), 5 deletions(-) create mode 100644 app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java create mode 100644 app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/ExternalLoginMarkerPasswordTest.java diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/CustomUserRegistry.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/CustomUserRegistry.java index 14d184f870..157e4fdd18 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/CustomUserRegistry.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/CustomUserRegistry.java @@ -153,7 +153,7 @@ else if(userDetails instanceof LdapUserDetails) { // for LDAP we don't store its password in the roller_users table, // just an string indicating external auth method being used. - unusedPassword = WebloggerConfig.getProperty("users.passwords.externalAuthValue",""); + unusedPassword = ExternalLoginAwarePasswordEncoder.externalLoginMarker(); ud.setPassword(unusedPassword); ud.setEnabled(enabled ? Boolean.TRUE : Boolean.FALSE); diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java index afe5949bd0..dad777028b 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java @@ -23,16 +23,41 @@ /** * Users who log in through LDAP or the servlet container have no Roller * password; Roller stores users.passwords.externalAuthValue in its place. - * That placeholder is not a password, so this encoder never matches it. + * That placeholder is not a password, so this encoder never matches it, nor + * the default placeholder, nor an empty password. */ public class ExternalLoginAwarePasswordEncoder implements PasswordEncoder { + /** Stored in place of a password when no other value is configured. */ + public static final String DEFAULT_EXTERNAL_LOGIN_MARKER = ""; + private final PasswordEncoder delegate; public ExternalLoginAwarePasswordEncoder(PasswordEncoder delegate) { this.delegate = delegate; } + /** + * The value stored in place of a Roller password for users who log in + * through LDAP or the servlet container: users.passwords.externalAuthValue, + * or the default when that setting is empty. + */ + public static String externalLoginMarker() { + String marker = WebloggerConfig.getProperty("users.passwords.externalAuthValue"); + return marker == null || marker.isEmpty() ? DEFAULT_EXTERNAL_LOGIN_MARKER : marker; + } + + /** + * Whether a password is the configured external-login marker or the + * default one, which accounts may still have stored from before the + * setting changed. Neither matches at login, so neither can be chosen as a + * Roller password. + */ + public static boolean isExternalLoginMarker(CharSequence password) { + return password != null && (externalLoginMarker().contentEquals(password) + || DEFAULT_EXTERNAL_LOGIN_MARKER.contentEquals(password)); + } + @Override public String encode(CharSequence rawPassword) { return delegate.encode(rawPassword); @@ -40,8 +65,7 @@ public String encode(CharSequence rawPassword) { @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { - String marker = WebloggerConfig.getProperty("users.passwords.externalAuthValue", ""); - if (rawPassword != null && marker != null && !marker.isEmpty() && marker.contentEquals(rawPassword)) { + if (rawPassword == null || rawPassword.length() == 0 || isExternalLoginMarker(rawPassword)) { return false; } return delegate.matches(rawPassword, encodedPassword); diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/admin/UserEdit.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/admin/UserEdit.java index 70878ecf82..90a2ef63d4 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/admin/UserEdit.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/admin/UserEdit.java @@ -40,6 +40,7 @@ import org.apache.roller.weblogger.ui.core.RollerLoginSessionManager; import org.apache.roller.weblogger.ui.struts2.core.Register; import org.apache.roller.weblogger.ui.struts2.util.UIAction; +import org.apache.roller.weblogger.ui.core.security.ExternalLoginAwarePasswordEncoder; import org.apache.struts2.interceptor.validation.SkipValidation; @@ -230,6 +231,10 @@ private boolean isAdd() { } private void myValidate() { + // the external-login marker never matches at login + if (ExternalLoginAwarePasswordEncoder.isExternalLoginMarker(getBean().getPassword())) { + addError("error.add.user.reservedPassword"); + } if (isAdd()) { String allowed = WebloggerConfig.getProperty("username.allowedChars"); if(allowed == null || allowed.isBlank()) { diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Profile.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Profile.java index 6f83a0ddb6..055cc5bef0 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Profile.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Profile.java @@ -28,6 +28,7 @@ import org.apache.roller.weblogger.config.WebloggerConfig; import org.apache.roller.weblogger.pojos.User; import org.apache.roller.weblogger.ui.struts2.util.UIAction; +import org.apache.roller.weblogger.ui.core.security.ExternalLoginAwarePasswordEncoder; import org.apache.struts2.interceptor.validation.SkipValidation; import java.util.Arrays; @@ -133,6 +134,10 @@ public String save() { } public void myValidate() { + // the external-login marker never matches at login + if (ExternalLoginAwarePasswordEncoder.isExternalLoginMarker(getBean().getPasswordText())) { + addError("error.add.user.reservedPassword"); + } if (StringUtils.isEmpty(getBean().getOpenIdUrl())) { // check that passwords match if they were specified (w/StringUtils.equals, null == null) if (!StringUtils.equals(getBean().getPasswordText(), getBean().getPasswordConfirm())) { 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..4fbcae0e50 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 @@ -39,6 +39,7 @@ import org.apache.roller.weblogger.ui.core.security.BootstrapSecurity; import org.apache.roller.weblogger.ui.struts2.util.UIAction; import org.apache.roller.weblogger.util.MailUtil; +import org.apache.roller.weblogger.ui.core.security.ExternalLoginAwarePasswordEncoder; import org.apache.struts2.convention.annotation.AllowedMethods; import org.apache.struts2.interceptor.ServletRequestAware; import org.apache.struts2.interceptor.validation.SkipValidation; @@ -356,7 +357,7 @@ public void myValidate() { if (usingSSO) { // store an unused marker in the Roller DB for the passphrase in // the LDAP or CMA cases, as actual passwords are stored externally - String unusedPassword = WebloggerConfig.getProperty("users.passwords.externalAuthValue", ""); + String unusedPassword = ExternalLoginAwarePasswordEncoder.externalLoginMarker(); // Preserve username and password, Spring Security case preserveUsernameAndPassword(unusedPassword); @@ -388,6 +389,12 @@ public void myValidate() { getBean().setPasswordConfirm(randomString); } + // the external-login marker is stored for users who log in elsewhere + // and never matches at login + if (!usingSSO && ExternalLoginAwarePasswordEncoder.isExternalLoginMarker(getBean().getPasswordText())) { + addError("error.add.user.reservedPassword"); + } + // check that passwords match if (!getBean().getPasswordText().equals(getBean().getPasswordConfirm())) { addError("userRegister.error.mismatchedPasswords"); diff --git a/app/src/main/resources/ApplicationResources.properties b/app/src/main/resources/ApplicationResources.properties index eb6a304856..8863ee0c79 100644 --- a/app/src/main/resources/ApplicationResources.properties +++ b/app/src/main/resources/ApplicationResources.properties @@ -452,6 +452,7 @@ error.add.user.openIdInUse=Open ID already in use with another account. error.add.user.missingUserName=You must specify a username. error.add.user.badUserName=Invalid user name (must be alpha-numerics only). error.add.user.missingPassword=You must specify a password. +error.add.user.reservedPassword=That password is reserved for accounts that log in elsewhere. Please choose a different password. error.add.user.invalid.timezone=Invalid timezone. error.add.user.invalid.locale=Invalid locale. error.upload.dirmax=You cannot exceed the maximum directory size of {0} MB. diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java new file mode 100644 index 0000000000..b9b3154ef6 --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java @@ -0,0 +1,208 @@ +/* + * 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.core; + +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import javax.servlet.ServletContext; + +import org.apache.roller.weblogger.TestUtils; +import org.apache.roller.weblogger.business.WebloggerFactory; +import org.apache.roller.weblogger.config.WebloggerConfig; +import org.apache.roller.weblogger.pojos.User; +import org.apache.roller.weblogger.ui.core.security.CustomUserRegistry; +import org.apache.roller.weblogger.ui.core.security.RollerUserDetailsService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.context.WebApplicationContext; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Users who log in through LDAP or the servlet container have a placeholder + * stored instead of a Roller password. The placeholder is not a password at + * the login form, whose provider RollerContext gives its password encoder. + */ +class ExternalLoginPlaceholderTest { + + private static final String DAO_PROVIDER = + "org.springframework.security.authentication.dao.DaoAuthenticationProvider#0"; + + private final Map savedProperties = new HashMap<>(); + private String userName; + + @BeforeEach + void setUp() throws Exception { + TestUtils.setupWeblogger(); + setProperty("passwds.encryption.enabled", "true"); + setProperty("passwds.encryption.algorithm", "bcrypt"); + setProperty("rememberme.enabled", "true"); + setProperty("securelogin.enabled", "false"); + } + + @AfterEach + void tearDown() throws Exception { + if (userName != null) { + TestUtils.teardownUser(userName); + TestUtils.endSession(true); + } + Properties config = config(); + savedProperties.forEach((k, v) -> { + if (v == null) { + config.remove(k); + } else { + config.setProperty(k, v); + } + }); + SecurityContextHolder.clearContext(); + } + + @Test + void anEncodedPlaceholderIsNotAPassword() throws Exception { + setProperty("authentication.method", "cma"); + DaoAuthenticationProvider provider = provider(); + // as Register stores it for container-managed sign-ups + User user = TestUtils.setupUser("cmauser"); + userName = user.getUserName(); + user.resetPassword(""); + WebloggerFactory.getWeblogger().getUserManager().saveUser(user); + TestUtils.endSession(true); + + assertThrows(AuthenticationException.class, () -> provider.authenticate( + new UsernamePasswordAuthenticationToken(userName, ""))); + } + + @Test + void anUnencodedPlaceholderIsNotAPassword() throws Exception { + setProperty("authentication.method", "db"); + setProperty("passwds.encryption.lazyUpgradeFrom", "plaintext"); + DaoAuthenticationProvider provider = provider(); + // as CustomUserRegistry stores it for directory users + User user = TestUtils.setupUser("ldapuser"); + userName = user.getUserName(); + user.setPassword(""); + WebloggerFactory.getWeblogger().getUserManager().saveUser(user); + TestUtils.endSession(true); + + assertThrows(AuthenticationException.class, () -> provider.authenticate( + new UsernamePasswordAuthenticationToken(userName, ""))); + } + + @Test + void theDefaultPlaceholderIsNotAPasswordUnderAnotherConfiguredValue() throws Exception { + setProperty("authentication.method", "db"); + setProperty("passwds.encryption.lazyUpgradeFrom", "plaintext"); + setProperty("users.passwords.externalAuthValue", ""); + DaoAuthenticationProvider provider = provider(); + // stored before the setting was changed + User user = TestUtils.setupUser("olduser"); + userName = user.getUserName(); + user.setPassword(""); + WebloggerFactory.getWeblogger().getUserManager().saveUser(user); + TestUtils.endSession(true); + + assertThrows(AuthenticationException.class, () -> provider.authenticate( + new UsernamePasswordAuthenticationToken(userName, ""))); + } + + @Test + void anEmptyConfiguredPlaceholderIsNotAPassword() throws Exception { + setProperty("authentication.method", "db"); + setProperty("passwds.encryption.lazyUpgradeFrom", "plaintext"); + setProperty("users.passwords.externalAuthValue", ""); + DaoAuthenticationProvider provider = provider(); + // as CustomUserRegistry stored an empty placeholder before + User user = TestUtils.setupUser("emptyuser"); + userName = user.getUserName(); + user.setPassword(""); + WebloggerFactory.getWeblogger().getUserManager().saveUser(user); + TestUtils.endSession(true); + + assertThrows(AuthenticationException.class, () -> provider.authenticate( + new UsernamePasswordAuthenticationToken(userName, ""))); + } + + @Test + void anOrdinaryPlaintextPasswordStillMatches() throws Exception { + setProperty("authentication.method", "db"); + setProperty("passwds.encryption.lazyUpgradeFrom", "plaintext"); + DaoAuthenticationProvider provider = provider(); + User user = TestUtils.setupUser("plainuser"); + userName = user.getUserName(); + user.setPassword("an ordinary password"); + WebloggerFactory.getWeblogger().getUserManager().saveUser(user); + TestUtils.endSession(true); + + assertTrue(provider.authenticate(new UsernamePasswordAuthenticationToken( + userName, "an ordinary password")).isAuthenticated()); + } + + @Test + void anEmptyConfiguredPlaceholderIsStoredAsTheDefault() throws Exception { + setProperty("authentication.method", "ldap"); + setProperty("users.passwords.externalAuthValue", ""); + SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken( + new org.springframework.security.core.userdetails.User("ldapuser", "unused", + List.of(new SimpleGrantedAuthority("editor"))), + null, List.of())); + + User user = CustomUserRegistry.getUserDetailsFromAuthentication(null); + + assertEquals("", user.getPassword()); + } + + /** The login form's provider, given its encoder the way RollerContext does at startup. */ + private static DaoAuthenticationProvider provider() { + DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); + provider.setUserDetailsService(new RollerUserDetailsService()); + WebApplicationContext ctx = mock(WebApplicationContext.class); + when(ctx.containsBean(DAO_PROVIDER)).thenReturn(true); + when(ctx.getBean(DAO_PROVIDER)).thenReturn(provider); + ServletContext servletContext = mock(ServletContext.class); + when(servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)) + .thenReturn(ctx); + new RollerContext().initializeSecurityFeatures(servletContext); + return provider; + } + + private void setProperty(String key, String value) throws ReflectiveOperationException { + Properties config = config(); + savedProperties.putIfAbsent(key, config.getProperty(key)); + config.setProperty(key, value); + } + + private static Properties config() throws ReflectiveOperationException { + Field field = WebloggerConfig.class.getDeclaredField("config"); + field.setAccessible(true); + return (Properties) field.get(null); + } +} diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/ExternalLoginMarkerPasswordTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/ExternalLoginMarkerPasswordTest.java new file mode 100644 index 0000000000..3ef37becb1 --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/ExternalLoginMarkerPasswordTest.java @@ -0,0 +1,203 @@ +/* + * 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.lang.reflect.Field; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +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.config.WebloggerConfig; +import org.apache.roller.weblogger.pojos.User; +import org.apache.roller.weblogger.ui.struts2.admin.UserEdit; +import org.apache.roller.weblogger.ui.struts2.util.UIAction; +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.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +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; + +/** + * Accounts that log in through LDAP or the servlet container store + * users.passwords.externalAuthValue instead of a password, and that value never + * matches at login. So nobody can choose it as a Roller password. + */ +class ExternalLoginMarkerPasswordTest { + + private static final String RESERVED = "error.add.user.reservedPassword"; + + private final Map savedProperties = new HashMap<>(); + private MockedStatic factory; + private UserManager users; + + @BeforeEach + void setUp() throws Exception { + setProperty("authentication.method", "db"); + setProperty("users.passwords.externalAuthValue", ""); + factory = mockStatic(WebloggerFactory.class); + users = mock(UserManager.class); + Weblogger weblogger = mock(Weblogger.class); + when(weblogger.getUserManager()).thenReturn(users); + factory.when(WebloggerFactory::getWeblogger).thenReturn(weblogger); + } + + @AfterEach + void tearDown() throws Exception { + factory.close(); + Properties config = config(); + savedProperties.forEach((k, v) -> { + if (v == null) { + config.remove(k); + } else { + config.setProperty(k, v); + } + }); + } + + @Test + void registrationRejectsTheMarker() { + Register action = withText(new Register()); + action.getBean().setUserName("newuser"); + action.getBean().setPasswordText(""); + action.getBean().setPasswordConfirm(""); + + action.myValidate(); + + assertTrue(action.getActionErrors().contains(RESERVED)); + } + + @Test + void registrationRejectsTheDefaultMarkerUnderAnotherConfiguredValue() throws Exception { + setProperty("users.passwords.externalAuthValue", ""); + for (String reserved : new String[] {"", ""}) { + Register action = withText(new Register()); + action.getBean().setUserName("newuser"); + action.getBean().setPasswordText(reserved); + action.getBean().setPasswordConfirm(reserved); + + action.myValidate(); + + assertTrue(action.getActionErrors().contains(RESERVED), reserved); + } + } + + @Test + void registrationAcceptsAnOrdinaryPassword() { + Register action = withText(new Register()); + action.getBean().setUserName("newuser"); + action.getBean().setPasswordText("an ordinary password"); + action.getBean().setPasswordConfirm("an ordinary password"); + + action.myValidate(); + + assertFalse(action.hasActionErrors()); + } + + @Test + void theProfileRejectsTheMarker() throws Exception { + User user = new User(); + user.setUserName("dbuser"); + user.setPassword("{bcrypt}existing"); + Profile action = withText(new Profile()); + action.setAuthenticatedUser(user); + action.getBean().setPasswordText(""); + action.getBean().setPasswordConfirm(""); + + assertEquals(UIAction.INPUT, action.save()); + + assertTrue(action.getActionErrors().contains(RESERVED)); + assertEquals("{bcrypt}existing", user.getPassword()); + verify(users, never()).saveUser(any()); + } + + @Test + void anAdministratorCannotGiveAUserTheMarker() throws Exception { + User admin = new User(); + admin.setUserName("admin"); + User user = new User(); + user.setId("user-1"); + user.setUserName("dbuser"); + user.setPassword("{bcrypt}existing"); + when(users.getUser("user-1")).thenReturn(user); + UserEdit action = withText(new UserEdit()); + action.setActionName("modifyUser"); + action.setAuthenticatedUser(admin); + action.getBean().setId("user-1"); + action.myPrepare(); + action.getBean().setPassword(""); + + assertEquals(UIAction.INPUT, action.save()); + + assertTrue(action.getActionErrors().contains(RESERVED)); + assertEquals("{bcrypt}existing", user.getPassword()); + verify(users, never()).saveUser(any()); + } + + @Test + void anAdministratorCannotCreateAUserWithTheMarker() throws Exception { + UserEdit action = withText(new UserEdit()); + User admin = new User(); + admin.setUserName("admin"); + action.setActionName("createUser"); + action.setAuthenticatedUser(admin); + action.myPrepare(); + action.getBean().setUserName("newuser"); + action.getBean().setPassword(""); + + assertEquals(UIAction.INPUT, action.save()); + + assertTrue(action.getActionErrors().contains(RESERVED)); + verify(users, never()).addUser(any()); + } + + private static T withText(T action) { + T spied = spy(action); + doAnswer(call -> call.getArgument(0)).when(spied).getText(anyString()); + doAnswer(call -> call.getArgument(0)).when(spied).getText(anyString(), anyList()); + doAnswer(call -> call.getArgument(0)).when(spied).getText(anyString(), anyString(), anyString()); + return spied; + } + + private void setProperty(String key, String value) throws ReflectiveOperationException { + Properties config = config(); + savedProperties.putIfAbsent(key, config.getProperty(key)); + config.setProperty(key, value); + } + + private static Properties config() throws ReflectiveOperationException { + Field field = WebloggerConfig.class.getDeclaredField("config"); + field.setAccessible(true); + return (Properties) field.get(null); + } +} From 4cec45d125ab42d803ec8ec601ecf7518f3b0441 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Tue, 17 Nov 2026 19:57:37 -0700 Subject: [PATCH 05/25] End a session after a password change even when its Roller session was dropped When the container passivates a session, RollerSession removes itself from it, and the next request rebuilt it from the login with the user's current password, so the session survived a password change. The session now keeps the login's user name and password digest in a separate attribute that outlives the Roller session, and a rebuild for that user ends the session when the password differs. PasswordChangeSessionTest covers a passivated session after a password change and one without a change. --- .../weblogger/ui/core/RollerSession.java | 28 ++++++++++ .../ui/core/PasswordChangeSessionTest.java | 54 +++++++++++++++++++ 2 files changed, 82 insertions(+) diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java index 0bb6a42e75..add005a43a 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java @@ -59,6 +59,10 @@ public class RollerSession public static final String ROLLER_SESSION = "org.apache.roller.weblogger.rollersession"; + // user name and password digest of the login, kept beside the Roller + // session so they outlive it when the container passivates the session + private static final String LOGIN_PASSWORD = ROLLER_SESSION + ".login"; + static{ WebloggerConfig.init(); // must be called before calls to logging APIs log = LogFactory.getLog(RollerSession.class); @@ -127,7 +131,13 @@ public static RollerSession getRollerSession(HttpServletRequest request) { } // only set authenticated user if user is enabled if (user != null && user.getEnabled()) { + // a login whose password changed since it was first + // seen ends here too, even with no Roller session left + if (!sameLoginPassword(session, user)) { + return endSession(request, session); + } rollerSession.setAuthenticatedUser(user); + rememberLoginPassword(session, rollerSession); } } catch (WebloggerException e) { @@ -153,7 +163,25 @@ public static void refreshPassword(HttpServletRequest request, User user) { if (attribute instanceof RollerSession && user.getUserName().equals(((RollerSession) attribute).userName)) { ((RollerSession) attribute).setAuthenticatedUser(user); + rememberLoginPassword(session, (RollerSession) attribute); + } + } + + /** + * Whether the login in this session first saw the user's current password, + * or the session has not recorded one for this user yet. + */ + private static boolean sameLoginPassword(HttpSession session, User user) { + Object recorded = session.getAttribute(LOGIN_PASSWORD); + String prefix = user.getUserName() + "\n"; + if (!(recorded instanceof String) || !((String) recorded).startsWith(prefix)) { + return true; } + return recorded.equals(prefix + digest(user)); + } + + private static void rememberLoginPassword(HttpSession session, RollerSession rollerSession) { + session.setAttribute(LOGIN_PASSWORD, rollerSession.userName + "\n" + rollerSession.passwordDigest); } /** diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java index 51be1eaa70..695d5fd88d 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java @@ -26,6 +26,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; +import javax.servlet.http.HttpSessionEvent; import org.apache.roller.weblogger.TestUtils; import org.apache.roller.weblogger.business.UserManager; import org.apache.roller.weblogger.business.WebloggerFactory; @@ -294,6 +295,49 @@ private static Field findField(Class type, String name) throws NoSuchFieldExc throw new NoSuchFieldException(name); } + @Test + void passwordChangeEndsASessionThatWasPassivated() throws Exception { + Browser a = new Browser(userName); + Browser b = new Browser(userName); + a.request(); + b.request(); + TestUtils.endSession(true); + + // the container saves b's session and restores it later, which drops + // the Roller session but keeps the login + b.passivate(); + + a.request(); + Profile profile = spy(new Profile()); + stubText(profile); + User self = user(userName); + ProfileBean bean = new ProfileBean(); + bean.copyFrom(self); + bean.setPasswordText("changed-password"); + bean.setPasswordConfirm("changed-password"); + profile.setBean(bean); + profile.setAuthenticatedUser(self); + profile.setServletRequest(a.httpRequest); + assertEquals(Profile.SUCCESS, profile.save()); + TestUtils.endSession(true); + + b.assertLoggedOut(); + // the session that changed the password keeps working after a restore + a.passivate(); + a.assertLoggedIn(userName); + } + + @Test + void passivatedSessionStaysLoggedInWithoutAPasswordChange() throws Exception { + Browser b = new Browser(userName); + b.request(); + TestUtils.endSession(true); + + b.passivate(); + + b.assertLoggedIn(userName); + } + private void saveAsAdmin(Browser admin, java.util.function.Consumer change) throws Exception { admin.request(); @@ -375,6 +419,11 @@ private HttpSession newSession() { attributes.put(call.getArgument(0), call.getArgument(1)); return null; }).when(s).setAttribute(anyString(), any()); + doAnswer(call -> { + checkValid(valid); + attributes.remove(call.getArgument(0)); + return null; + }).when(s).removeAttribute(anyString()); doAnswer(call -> { checkValid(valid); valid[0] = false; @@ -394,6 +443,11 @@ private static void checkValid(boolean[] valid) { } } + /** The container saves this session and restores it later. */ + void passivate() { + new RollerSession().sessionWillPassivate(new HttpSessionEvent(session)); + } + RollerSession request() { if (ended) { SecurityContextHolder.clearContext(); From 09ff2d2fd333182982f5fd34d05147229bac353f Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Tue, 17 Nov 2026 21:46:38 -0700 Subject: [PATCH 06/25] Don't let a stored external-login marker reach the delegate encoder --- .../ExternalLoginAwarePasswordEncoder.java | 5 ++++- .../ui/core/ExternalLoginPlaceholderTest.java | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java index dad777028b..55681f44a1 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java @@ -65,7 +65,10 @@ public String encode(CharSequence rawPassword) { @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { - if (rawPassword == null || rawPassword.length() == 0 || isExternalLoginMarker(rawPassword)) { + // a stored marker is checked before the delegate sees it, since a + // marker such as {noop}secret would otherwise match its own suffix + if (rawPassword == null || rawPassword.length() == 0 || isExternalLoginMarker(rawPassword) + || isExternalLoginMarker(encodedPassword)) { return false; } return delegate.matches(rawPassword, encodedPassword); diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java index b9b3154ef6..a4a01bb291 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java @@ -151,6 +151,22 @@ void anEmptyConfiguredPlaceholderIsNotAPassword() throws Exception { new UsernamePasswordAuthenticationToken(userName, ""))); } + @Test + void aStoredPlaceholderWithAnEncoderPrefixIsNotAPassword() throws Exception { + setProperty("authentication.method", "ldap"); + setProperty("users.passwords.externalAuthValue", "{noop}secret"); + DaoAuthenticationProvider provider = provider(); + // as CustomUserRegistry stores the configured placeholder + User user = TestUtils.setupUser("prefixuser"); + userName = user.getUserName(); + user.setPassword("{noop}secret"); + WebloggerFactory.getWeblogger().getUserManager().saveUser(user); + TestUtils.endSession(true); + + assertThrows(AuthenticationException.class, () -> provider.authenticate( + new UsernamePasswordAuthenticationToken(userName, "secret"))); + } + @Test void anOrdinaryPlaintextPasswordStillMatches() throws Exception { setProperty("authentication.method", "db"); From d984431e6c19748c4ea0c855897169ebb6c9161b Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Wed, 18 Nov 2026 21:18:50 -0700 Subject: [PATCH 07/25] Make registration null-safe and use one external-login marker for remember-me Registering without a password outside db mode no longer throws a NullPointerException when the passwords are compared. The remember-me signature for LDAP users now takes its placeholder from ExternalLoginAwarePasswordEncoder.externalLoginMarker(), so an empty users.passwords.externalAuthValue means the default there as it does everywhere else. With the default configuration the value is unchanged, so existing remember-me cookies stay valid. The tests now restore WebloggerConfig properties even when user teardown fails or the original value was not set, and put back the password encoder that RollerContext shares. --- .../security/RollerRememberMeServices.java | 2 +- .../weblogger/ui/struts2/core/Register.java | 2 +- .../ui/core/ExternalLoginPlaceholderTest.java | 68 +++++++++++++++---- .../core/ExternalLoginMarkerPasswordTest.java | 16 ++++- 4 files changed, 72 insertions(+), 16 deletions(-) diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerRememberMeServices.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerRememberMeServices.java index 2566a4308d..81042651fc 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerRememberMeServices.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerRememberMeServices.java @@ -64,7 +64,7 @@ protected String makeTokenSignature(long tokenExpiryTime, String username, Strin // for LDAP we don't store its password in the roller_users table, // just an string indicating external auth method being used. - password = WebloggerConfig.getProperty("users.passwords.externalAuthValue",""); + password = ExternalLoginAwarePasswordEncoder.externalLoginMarker(); } String data = username + ":" + tokenExpiryTime + ":" + password + ":" + getKey(); 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 4fbcae0e50..15172bdbdc 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 @@ -396,7 +396,7 @@ public void myValidate() { } // check that passwords match - if (!getBean().getPasswordText().equals(getBean().getPasswordConfirm())) { + if (!StringUtils.equals(getBean().getPasswordText(), getBean().getPasswordConfirm())) { addError("userRegister.error.mismatchedPasswords"); } diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java index a4a01bb291..226feb0598 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java @@ -30,6 +30,7 @@ import org.apache.roller.weblogger.config.WebloggerConfig; import org.apache.roller.weblogger.pojos.User; import org.apache.roller.weblogger.ui.core.security.CustomUserRegistry; +import org.apache.roller.weblogger.ui.core.security.RollerRememberMeServices; import org.apache.roller.weblogger.ui.core.security.RollerUserDetailsService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -59,9 +60,11 @@ class ExternalLoginPlaceholderTest { private final Map savedProperties = new HashMap<>(); private String userName; + private Object savedEncoder; @BeforeEach void setUp() throws Exception { + savedEncoder = encoderField().get(null); TestUtils.setupWeblogger(); setProperty("passwds.encryption.enabled", "true"); setProperty("passwds.encryption.algorithm", "bcrypt"); @@ -71,19 +74,24 @@ void setUp() throws Exception { @AfterEach void tearDown() throws Exception { - if (userName != null) { - TestUtils.teardownUser(userName); - TestUtils.endSession(true); - } - Properties config = config(); - savedProperties.forEach((k, v) -> { - if (v == null) { - config.remove(k); - } else { - config.setProperty(k, v); + try { + if (userName != null) { + TestUtils.teardownUser(userName); + TestUtils.endSession(true); } - }); - SecurityContextHolder.clearContext(); + } finally { + Properties config = config(); + savedProperties.forEach((k, v) -> { + if (v == null) { + config.remove(k); + } else { + config.setProperty(k, v); + } + }); + SecurityContextHolder.clearContext(); + // provider() replaces the encoder RollerContext shares + encoderField().set(null, savedEncoder); + } } @Test @@ -196,6 +204,31 @@ void anEmptyConfiguredPlaceholderIsStoredAsTheDefault() throws Exception { assertEquals("", user.getPassword()); } + @Test + void theRememberMeSignatureUsesTheDefaultForAnEmptyConfiguredPlaceholder() throws Exception { + setProperty("authentication.method", "ldap"); + setProperty("rememberme.enabled", "false"); + SigningRememberMeServices services = new SigningRememberMeServices(); + setProperty("users.passwords.externalAuthValue", ""); + String signedWithTheDefault = services.sign(); + + // CustomUserRegistry stores the default for an empty setting + setProperty("users.passwords.externalAuthValue", ""); + + assertEquals(signedWithTheDefault, services.sign()); + } + + private static class SigningRememberMeServices extends RollerRememberMeServices { + + SigningRememberMeServices() { + super(new RollerUserDetailsService()); + } + + String sign() { + return makeTokenSignature(1L, "ldapuser", "unused"); + } + } + /** The login form's provider, given its encoder the way RollerContext does at startup. */ private static DaoAuthenticationProvider provider() { DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); @@ -212,10 +245,19 @@ private static DaoAuthenticationProvider provider() { private void setProperty(String key, String value) throws ReflectiveOperationException { Properties config = config(); - savedProperties.putIfAbsent(key, config.getProperty(key)); + // keep the first value seen, even when it is null (not set) + if (!savedProperties.containsKey(key)) { + savedProperties.put(key, config.getProperty(key)); + } config.setProperty(key, value); } + private static Field encoderField() throws ReflectiveOperationException { + Field field = RollerContext.class.getDeclaredField("encoder"); + field.setAccessible(true); + return field; + } + private static Properties config() throws ReflectiveOperationException { Field field = WebloggerConfig.class.getDeclaredField("config"); field.setAccessible(true); diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/ExternalLoginMarkerPasswordTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/ExternalLoginMarkerPasswordTest.java index 3ef37becb1..3d9389e6f5 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/ExternalLoginMarkerPasswordTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/ExternalLoginMarkerPasswordTest.java @@ -34,6 +34,7 @@ import org.junit.jupiter.api.Test; 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; @@ -124,6 +125,16 @@ void registrationAcceptsAnOrdinaryPassword() { assertFalse(action.hasActionErrors()); } + @Test + void registrationWithoutAPasswordDoesNotFail() throws Exception { + // db-openid does not require a password when the form is validated + setProperty("authentication.method", "db-openid"); + Register action = withText(new Register()); + action.getBean().setUserName("newuser"); + + assertDoesNotThrow(action::myValidate); + } + @Test void theProfileRejectsTheMarker() throws Exception { User user = new User(); @@ -191,7 +202,10 @@ private static T withText(T action) { private void setProperty(String key, String value) throws ReflectiveOperationException { Properties config = config(); - savedProperties.putIfAbsent(key, config.getProperty(key)); + // keep the first value seen, even when it is null (not set) + if (!savedProperties.containsKey(key)) { + savedProperties.put(key, config.getProperty(key)); + } config.setProperty(key, value); } From 0d3602def6fc5caf3f5105b55d58771cf60f86ce Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Wed, 18 Nov 2026 21:22:14 -0700 Subject: [PATCH 08/25] Record the login password at authentication time A login is now recorded in its session when Spring Security accepts it, from the form login and single sign-on success handlers and from the remember-me services, instead of on the first request to the Roller UI. A login that had only visited weblog pages before the password changed no longer adopts the new password and survives, and logging in again in a browser that still had a stale session is no longer ended on its next request. A request that finds its session already invalidated by a parallel request is treated as logged out instead of failing with an IllegalStateException. Profile and user admin saves compare OpenID URLs without their trailing slash, so saving an unchanged profile no longer regenerates the stored password and ends the other sessions of the user. --- .../weblogger/ui/core/RollerSession.java | 86 +++++- .../security/RollerLoginSuccessHandler.java | 50 ++++ .../security/RollerRememberMeServices.java | 15 ++ .../weblogger/ui/struts2/admin/UserEdit.java | 3 +- .../weblogger/ui/struts2/core/Profile.java | 3 +- app/src/main/webapp/WEB-INF/security.xml | 18 +- .../ui/core/PasswordChangeSessionTest.java | 245 +++++++++++++++++- 7 files changed, 397 insertions(+), 23 deletions(-) create mode 100644 app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerLoginSuccessHandler.java diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java index add005a43a..31db01ef12 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java @@ -72,8 +72,21 @@ public class RollerSession * Get RollerSession from request (and add user if not already present). */ public static RollerSession getRollerSession(HttpServletRequest request) { - RollerSession rollerSession = null; HttpSession session = request.getSession(false); + try { + return getRollerSession(request, session); + } catch (IllegalStateException e) { + if (session == null || !isInvalidated(session)) { + throw e; + } + // another request of the same browser ended the session while + // this one was using it, so this one is logged out too + return endSession(request, session); + } + } + + private static RollerSession getRollerSession(HttpServletRequest request, HttpSession session) { + RollerSession rollerSession = null; if (session != null) { rollerSession = (RollerSession)session.getAttribute(ROLLER_SESSION); @@ -108,13 +121,8 @@ public static RollerSession getRollerSession(HttpServletRequest request) { try { UserManager umgr = WebloggerFactory.getWeblogger().getUserManager(); - User user = umgr.getUserByUserName(principal.getName()); - - // check for OpenID username (in the form of a URL) - if (user == null && OpenIdUrls.isOpenIdUrl(principal.getName())) { - user = umgr.getUserByOpenIdUrl(OpenIdUrls.normalize(principal.getName())); - } - + User user = findUser(umgr, principal); + // try one time to auto-provision, only happens if user==null // which means installation has LDAP enabled in security.xml if (user == null && WebloggerConfig.getBooleanProperty("users.ldap.autoProvision.enabled")) { @@ -149,6 +157,42 @@ public static RollerSession getRollerSession(HttpServletRequest request) { return rollerSession; } + /** + * The enabled user a login belongs to, or null if there is none. + */ + private static User findUser(UserManager umgr, Principal principal) throws WebloggerException { + User user = umgr.getUserByUserName(principal.getName()); + + // check for OpenID username (in the form of a URL) + if (user == null && OpenIdUrls.isOpenIdUrl(principal.getName())) { + user = umgr.getUserByOpenIdUrl(OpenIdUrls.normalize(principal.getName())); + } + return user; + } + + /** + * Records a login in its session as soon as Spring Security accepts it: + * the user's password as it is now, so that a later password change ends + * the session even if Roller's pages are not opened in between. A login in + * a session that already had one replaces what that one left behind. + */ + public static void loggedIn(HttpServletRequest request, Principal login) { + try { + HttpSession session = request.getSession(true); + session.removeAttribute(ROLLER_SESSION); + session.removeAttribute(LOGIN_PASSWORD); + if (WebloggerFactory.isBootstrapped()) { + UserManager umgr = WebloggerFactory.getWeblogger().getUserManager(); + User user = findUser(umgr, login); + if (user != null) { + session.setAttribute(LOGIN_PASSWORD, user.getUserName() + "\n" + digest(user)); + } + } + } catch (WebloggerException e) { + log.error("ERROR: getting user object", e); + } + } + /** * Keeps the current session logged in after its own user changed their * password, or an administrator changed their own. Call it after the new @@ -159,11 +203,18 @@ public static void refreshPassword(HttpServletRequest request, User user) { if (session == null || user == null) { return; } - Object attribute = session.getAttribute(ROLLER_SESSION); - if (attribute instanceof RollerSession - && user.getUserName().equals(((RollerSession) attribute).userName)) { - ((RollerSession) attribute).setAuthenticatedUser(user); - rememberLoginPassword(session, (RollerSession) attribute); + try { + Object attribute = session.getAttribute(ROLLER_SESSION); + if (attribute instanceof RollerSession + && user.getUserName().equals(((RollerSession) attribute).userName)) { + ((RollerSession) attribute).setAuthenticatedUser(user); + rememberLoginPassword(session, (RollerSession) attribute); + } + } catch (IllegalStateException e) { + if (!isInvalidated(session)) { + throw e; + } + // another request ended the session, there is no login to keep } } @@ -202,6 +253,15 @@ private boolean isCurrent() { return user != null && digest(user).equals(passwordDigest); } + private static boolean isInvalidated(HttpSession session) { + try { + session.getCreationTime(); + return false; + } catch (IllegalStateException e) { + return true; + } + } + /** * Ends a session whose login no longer holds: invalidates it, clears the * login from this request, and gives the rest of the request a new diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerLoginSuccessHandler.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerLoginSuccessHandler.java new file mode 100644 index 0000000000..2b984c7a3a --- /dev/null +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerLoginSuccessHandler.java @@ -0,0 +1,50 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * 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.core.security; + +import java.io.IOException; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.apache.roller.weblogger.ui.core.RollerSession; +import org.springframework.security.core.Authentication; +import org.springframework.security.web.authentication.AuthenticationSuccessHandler; + +/** + * Records a successful login in its session, then lets another handler send + * the user on. Roller ends a session when its user's password is no longer + * the one recorded here. + */ +public class RollerLoginSuccessHandler implements AuthenticationSuccessHandler { + + private final AuthenticationSuccessHandler next; + + public RollerLoginSuccessHandler(AuthenticationSuccessHandler next) { + this.next = next; + } + + @Override + public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, + Authentication authentication) throws IOException, ServletException { + RollerSession.loggedIn(request, authentication); + next.onAuthenticationSuccess(request, response, authentication); + } +} diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerRememberMeServices.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerRememberMeServices.java index 2566a4308d..bbf97e29b6 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerRememberMeServices.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerRememberMeServices.java @@ -22,10 +22,14 @@ import org.apache.commons.logging.LogFactory; import org.apache.roller.weblogger.config.AuthMethod; import org.apache.roller.weblogger.config.WebloggerConfig; +import org.apache.roller.weblogger.ui.core.RollerSession; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.codec.Hex; import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices; +import javax.servlet.http.HttpServletRequest; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -49,6 +53,17 @@ public RollerRememberMeServices(UserDetailsService userDetailsService) { log.debug("initialized: RollerRememberMeServices with key"); } + /** + * Records the login a remember-me cookie stands for in its session, as a + * login form does. + */ + @Override + protected Authentication createSuccessfulAuthentication(HttpServletRequest request, UserDetails user) { + Authentication login = super.createSuccessfulAuthentication(request, user); + RollerSession.loggedIn(request, login); + return login; + } + /** * Calculates the digital signature to be put in the cookie. Default value is * SHA-512 ("username:tokenExpiryTime:password:key") diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/admin/UserEdit.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/admin/UserEdit.java index 3e1d8a11a0..0cf413d43c 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/admin/UserEdit.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/admin/UserEdit.java @@ -170,7 +170,8 @@ public String save() { if ((authMethod.equals(AuthMethod.OPENID) || (authMethod.equals(AuthMethod.DB_OPENID) && !StringUtils.isEmpty(bean.getOpenIdUrl()))) && (StringUtils.isEmpty(user.getPassword()) - || !StringUtils.equals(previousOpenIdUrl, user.getOpenIdUrl()))) { + || !StringUtils.equals(StringUtils.removeEnd(previousOpenIdUrl, "/"), + StringUtils.removeEnd(user.getOpenIdUrl(), "/")))) { String randomString = RandomStringUtils.randomAlphanumeric(255); user.resetPassword(randomString); } diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Profile.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Profile.java index 2f44a7b2d9..fb80918466 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Profile.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Profile.java @@ -118,7 +118,8 @@ public String save() { if ((authMethod.equals(AuthMethod.OPENID) || (authMethod.equals(AuthMethod.DB_OPENID) && !StringUtils.isEmpty(bean.getOpenIdUrl()))) && (StringUtils.isEmpty(existingUser.getPassword()) - || !StringUtils.equals(previousOpenIdUrl, existingUser.getOpenIdUrl()))) { + || !StringUtils.equals(StringUtils.removeEnd(previousOpenIdUrl, "/"), + StringUtils.removeEnd(existingUser.getOpenIdUrl(), "/")))) { String randomString = RandomStringUtils.randomAlphanumeric(255); existingUser.resetPassword(randomString); } diff --git a/app/src/main/webapp/WEB-INF/security.xml b/app/src/main/webapp/WEB-INF/security.xml index 18ed9206a2..2d31c47f27 100644 --- a/app/src/main/webapp/WEB-INF/security.xml +++ b/app/src/main/webapp/WEB-INF/security.xml @@ -41,6 +41,7 @@ username-parameter="j_username" password-parameter="j_password" authentication-failure-url="/roller-ui/login.rol?error=true" + authentication-success-handler-ref="formLoginSuccessHandler" login-processing-url="/roller_j_security_check"/> + + + + + + + - + class="org.apache.roller.weblogger.ui.core.security.RollerLoginSuccessHandler"> + + + + + bean.setPassword("reset-password")); + + b.assertLoggedOut(); + } + + @Test + void loggingInAgainInAStaleSessionStaysLoggedIn() throws Exception { + Browser a = new Browser(userName); + Browser b = new Browser(userName); + a.request(); + b.request(); + TestUtils.endSession(true); + + changeOwnPassword(a); + + // b still has its old session and logs in again with the new + // password before making any other request + b.login(); + b.assertLoggedIn(userName); + a.assertLoggedIn(userName); + } + + @Test + void loggingInAsAnotherUserInTheSameSessionSwitchesUser() throws Exception { + Browser b = new Browser(userName); + assertEquals(userName, b.request().getAuthenticatedUser().getUserName()); + TestUtils.endSession(true); + + b.login(UsernamePasswordAuthenticationToken.authenticated(adminName, null, List.of())); + + b.assertLoggedIn(adminName); + } + + @Test + void requestOnASessionEndedByAnotherRequestIsLoggedOut() throws Exception { + Browser b = new Browser(userName); + b.request(); + TestUtils.endSession(true); + + b.sessionEndsDuringNextRequest(); + + b.assertLoggedOut(); + } + + @Test + void savingAProfileOnASessionEndedByAnotherRequestDoesNotFail() throws Exception { + Browser b = new Browser(userName); + b.request(); + TestUtils.endSession(true); + + b.sessionEndsDuringNextRequest(); + + assertDoesNotThrow(() -> RollerSession.refreshPassword(b.httpRequest, user(userName))); + } + + @Test + void openIdProfileEditKeepsSessionsWhenTheStoredUrlEndsWithASlash() throws Exception { + linkOpenId(userName, "https://openid.example.com/sessionuser/"); + Browser a = new Browser(userName); + Browser b = new Browser(userName); + a.request(); + b.request(); + TestUtils.endSession(true); + String storedPassword = user(userName).getPassword(); + + a.request(); + Profile profile = spy(new Profile()); + stubText(profile); + setAuthMethod(profile, AuthMethod.OPENID); + User self = user(userName); + ProfileBean bean = new ProfileBean(); + bean.copyFrom(self); + bean.setScreenName("Renamed"); + profile.setBean(bean); + profile.setAuthenticatedUser(self); + profile.setServletRequest(a.httpRequest); + assertEquals(Profile.SUCCESS, profile.save(), () -> String.valueOf(profile.getActionErrors())); + TestUtils.endSession(true); + + assertEquals(storedPassword, user(userName).getPassword()); + b.assertLoggedIn(userName); + a.assertLoggedIn(userName); + } + + @Test + void adminEditKeepsSessionsWhenOnlyATrailingSlashIsAdded() throws Exception { + linkOpenId(userName, "https://openid.example.com/sessionuser"); + Browser admin = new Browser(adminName); + Browser b = new Browser(userName); + admin.request(); + b.request(); + TestUtils.endSession(true); + String storedPassword = user(userName).getPassword(); + + admin.request(); + UserEdit action = userEdit(admin, userName); + setAuthMethod(action, AuthMethod.DB_OPENID); + action.getBean().setOpenIdUrl("https://openid.example.com/sessionuser/"); + assertEquals(UserEdit.SUCCESS, action.save(), () -> String.valueOf(action.getActionErrors())); + TestUtils.endSession(true); + + assertEquals(storedPassword, user(userName).getPassword()); + b.assertLoggedIn(userName); + } + + /** The user of this browser changes their own password on the profile page. */ + private void changeOwnPassword(Browser a) throws Exception { + a.request(); + Profile profile = spy(new Profile()); + stubText(profile); + User self = user(a.login.getName()); + ProfileBean bean = new ProfileBean(); + bean.copyFrom(self); + bean.setPasswordText("changed-password"); + bean.setPasswordConfirm("changed-password"); + profile.setBean(bean); + profile.setAuthenticatedUser(self); + profile.setServletRequest(a.httpRequest); + assertEquals(Profile.SUCCESS, profile.save(), () -> String.valueOf(profile.getActionErrors())); + TestUtils.endSession(true); + } + private void saveAsAdmin(Browser admin, java.util.function.Consumer change) throws Exception { admin.request(); @@ -386,17 +551,33 @@ private static PasswordEncoder swapEncoder(PasswordEncoder encoder) throws Excep */ private static final class Browser { final HttpServletRequest httpRequest = mock(HttpServletRequest.class); - final Authentication login; + Authentication login; HttpSession session; // the session holding the login was invalidated boolean ended; + // a session another request invalidated after this one picked it up + HttpSession endedUnderneath; Browser(String name) { - login = UsernamePasswordAuthenticationToken.authenticated(name, null, List.of()); + this(UsernamePasswordAuthenticationToken.authenticated(name, null, List.of())); + } + + Browser(Authentication authentication) { + this(authentication, false); + } + + private Browser(Authentication authentication, boolean remembered) { session = newSession(); - // keep reporting the original login, so a rebuild from it would show - when(httpRequest.getUserPrincipal()).thenReturn(login); - when(httpRequest.getSession(false)).thenAnswer(call -> session); + // keep reporting the login, so a rebuild from it would show + when(httpRequest.getUserPrincipal()).thenAnswer(call -> login); + when(httpRequest.getSession(false)).thenAnswer(call -> { + if (endedUnderneath != null) { + HttpSession stale = endedUnderneath; + endedUnderneath = null; + return stale; + } + return session; + }); when(httpRequest.getSession(true)).thenAnswer(call -> { if (session == null) { session = newSession(); @@ -404,6 +585,54 @@ private static final class Browser { return session; }); when(httpRequest.getSession()).thenAnswer(call -> httpRequest.getSession(true)); + if (remembered) { + rememberMeLogin(authentication.getName()); + } else { + login(authentication); + } + } + + /** A browser whose remember-me cookie logged it in. */ + static Browser remembered(String name) { + return new Browser(UsernamePasswordAuthenticationToken.authenticated(name, null, List.of()), true); + } + + /** Logs in again with the same account, in the session it has. */ + void login() { + login(login); + } + + /** Spring authenticated a login form or an OpenID sign-in. */ + void login(Authentication authentication) { + login = authentication; + ended = false; + try { + new RollerLoginSuccessHandler((request, response, auth) -> { }) + .onAuthenticationSuccess(httpRequest, mock(HttpServletResponse.class), login); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + /** Spring accepted the browser's remember-me cookie. */ + private void rememberMeLogin(String name) { + UserDetails details = org.springframework.security.core.userdetails.User + .withUsername(name).password("stored-hash").authorities(List.of()).build(); + login = new RollerRememberMeServices(userName -> details) { + Authentication accept() { + return createSuccessfulAuthentication(httpRequest, details); + } + }.accept(); + } + + /** + * Another request of this browser ends the session just after the + * next request has picked it up. + */ + void sessionEndsDuringNextRequest() { + HttpSession current = session; + current.invalidate(); + endedUnderneath = current; } private HttpSession newSession() { @@ -424,6 +653,10 @@ private HttpSession newSession() { attributes.remove(call.getArgument(0)); return null; }).when(s).removeAttribute(anyString()); + when(s.getCreationTime()).thenAnswer(call -> { + checkValid(valid); + return 0L; + }); doAnswer(call -> { checkValid(valid); valid[0] = false; @@ -449,7 +682,7 @@ void passivate() { } RollerSession request() { - if (ended) { + if (ended && endedUnderneath == null) { SecurityContextHolder.clearContext(); } else { SecurityContextHolder.getContext().setAuthentication(login); From 9a82d5b5737f21ea08e4eb1abb0cc4f79e31ef60 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Wed, 18 Nov 2026 21:54:55 -0700 Subject: [PATCH 09/25] Test that security.xml records the password digest on every login The login hooks that record the password digest are set up only in security.xml, so this test loads that file and checks that the form login filter, the single sign-on filter and remember-me all use them. It fails if the success handler or the remember-me services reference is removed. --- .../security/SecurityXmlLoginWiringTest.java | 112 ++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 app/src/test/java/org/apache/roller/weblogger/ui/core/security/SecurityXmlLoginWiringTest.java diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/security/SecurityXmlLoginWiringTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/security/SecurityXmlLoginWiringTest.java new file mode 100644 index 0000000000..7ab31d1bc3 --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/security/SecurityXmlLoginWiringTest.java @@ -0,0 +1,112 @@ +/* + * 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.core.security; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; + +import org.apache.roller.weblogger.TestUtils; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.context.support.GenericXmlApplicationContext; +import org.springframework.core.io.FileSystemResource; +import org.springframework.security.web.FilterChainProxy; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Every way of logging in that security.xml sets up records the login in its + * session, which is what lets a later password change end that session. + */ +class SecurityXmlLoginWiringTest { + + private static GenericXmlApplicationContext context; + private static final List filters = new ArrayList<>(); + + @BeforeAll + static void loadSecurityXml() throws Exception { + TestUtils.setupWeblogger(); + context = new GenericXmlApplicationContext( + new FileSystemResource("src/main/webapp/WEB-INF/security.xml")); + for (SecurityFilterChain chain : context.getBean(FilterChainProxy.class).getFilterChains()) { + filters.addAll(chain.getFilters()); + } + } + + @AfterAll + static void close() { + if (context != null) { + context.close(); + } + } + + @Test + void formLoginRecordsTheLogin() throws Exception { + long formLogins = 0; + for (Object filter : filters) { + if (filter instanceof UsernamePasswordAuthenticationFilter) { + formLogins++; + assertInstanceOf(RollerLoginSuccessHandler.class, successHandler(filter)); + } + } + assertEquals(1, formLogins, "security.xml should set up one form login"); + } + + @Test + void everyLoginFilterRecordsTheLogin() throws Exception { + long loginFilters = 0; + for (Object filter : filters) { + if (filter instanceof AbstractAuthenticationProcessingFilter) { + loginFilters++; + assertInstanceOf(RollerLoginSuccessHandler.class, successHandler(filter), + filter.getClass().getSimpleName() + " should record the login"); + } + } + // the login form and single sign-on + assertTrue(loginFilters >= 2, "expected the form and single sign-on filters, found " + loginFilters); + } + + @Test + void rememberMeRecordsTheLogin() { + long rememberMeFilters = 0; + for (Object filter : filters) { + if (filter instanceof RememberMeAuthenticationFilter) { + rememberMeFilters++; + assertInstanceOf(RollerRememberMeServices.class, + ((RememberMeAuthenticationFilter) filter).getRememberMeServices()); + } + } + assertEquals(1, rememberMeFilters, "security.xml should set up remember-me"); + } + + private static Object successHandler(Object filter) throws Exception { + Field field = AbstractAuthenticationProcessingFilter.class.getDeclaredField("successHandler"); + field.setAccessible(true); + return field.get(filter); + } +} From 8c48ca3b8faaf4f1cebeb416c084ad56f5fd2417 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Thu, 19 Nov 2026 17:28:24 -0700 Subject: [PATCH 10/25] Recognize previously configured external-login markers Accounts created before users.passwords.externalAuthValue changed still have the old marker stored, encoded or not, and the encoder only recognized the current marker and the default, so the old marker matched at login. The new users.passwords.externalAuthValue.previous setting lists earlier markers, which are refused at login and can't be chosen as passwords, the same as the current one. Empty entries are ignored so an empty password never counts as a marker. --- .../ExternalLoginAwarePasswordEncoder.java | 29 +++++++++--- .../roller/weblogger/config/roller.properties | 5 ++ .../ui/core/ExternalLoginPlaceholderTest.java | 47 +++++++++++++++++++ 3 files changed, 74 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java index 55681f44a1..1c0e0bf7bc 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java @@ -17,6 +17,7 @@ package org.apache.roller.weblogger.ui.core.security; +import org.apache.commons.lang3.StringUtils; import org.apache.roller.weblogger.config.WebloggerConfig; import org.springframework.security.crypto.password.PasswordEncoder; @@ -24,7 +25,7 @@ * Users who log in through LDAP or the servlet container have no Roller * password; Roller stores users.passwords.externalAuthValue in its place. * That placeholder is not a password, so this encoder never matches it, nor - * the default placeholder, nor an empty password. + * the default or a previous placeholder, nor an empty password. */ public class ExternalLoginAwarePasswordEncoder implements PasswordEncoder { @@ -48,14 +49,28 @@ public static String externalLoginMarker() { } /** - * Whether a password is the configured external-login marker or the - * default one, which accounts may still have stored from before the - * setting changed. Neither matches at login, so neither can be chosen as a - * Roller password. + * Whether a password is the configured external-login marker, the default + * one, or one listed in users.passwords.externalAuthValue.previous, which + * accounts may still have stored from before the setting changed. None of + * them matches at login, so none can be chosen as a Roller password. */ public static boolean isExternalLoginMarker(CharSequence password) { - return password != null && (externalLoginMarker().contentEquals(password) - || DEFAULT_EXTERNAL_LOGIN_MARKER.contentEquals(password)); + if (password == null) { + return false; + } + if (externalLoginMarker().contentEquals(password) + || DEFAULT_EXTERNAL_LOGIN_MARKER.contentEquals(password)) { + return true; + } + String previous = WebloggerConfig.getProperty("users.passwords.externalAuthValue.previous"); + for (String marker : StringUtils.split(StringUtils.defaultString(previous), ',')) { + // an empty entry is never a marker, so an empty password isn't one + String trimmed = marker.trim(); + if (!trimmed.isEmpty() && trimmed.contentEquals(password)) { + return true; + } + } + return false; } @Override diff --git a/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties b/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties index 91979b2b2b..074a930cc6 100644 --- a/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties +++ b/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties @@ -364,6 +364,11 @@ weblog.inlineImages.maxFieldBytes=60000 # openid presently generates a random (long) password string instead. users.passwords.externalAuthValue= +# Comma-separated values that users.passwords.externalAuthValue had before. +# Accounts created then still have them stored, so list them here when changing +# that setting; none of them is accepted as a password. +users.passwords.externalAuthValue.previous= + # Password security settings passwds.encryption.enabled=true passwds.encryption.algorithm=bcrypt diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java index 226feb0598..6443498bc6 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java @@ -30,6 +30,7 @@ import org.apache.roller.weblogger.config.WebloggerConfig; import org.apache.roller.weblogger.pojos.User; import org.apache.roller.weblogger.ui.core.security.CustomUserRegistry; +import org.apache.roller.weblogger.ui.core.security.ExternalLoginAwarePasswordEncoder; import org.apache.roller.weblogger.ui.core.security.RollerRememberMeServices; import org.apache.roller.weblogger.ui.core.security.RollerUserDetailsService; import org.junit.jupiter.api.AfterEach; @@ -43,6 +44,7 @@ import org.springframework.web.context.WebApplicationContext; 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.Mockito.mock; @@ -142,6 +144,51 @@ void theDefaultPlaceholderIsNotAPasswordUnderAnotherConfiguredValue() throws Exc new UsernamePasswordAuthenticationToken(userName, ""))); } + @Test + void aPreviousEncodedPlaceholderIsNotAPasswordAfterTheSettingChanges() throws Exception { + setProperty("authentication.method", "cma"); + setProperty("users.passwords.externalAuthValue", ""); + DaoAuthenticationProvider provider = provider(); + // as Register stored it for container-managed sign-ups + User user = TestUtils.setupUser("oldcmauser"); + userName = user.getUserName(); + user.resetPassword(""); + WebloggerFactory.getWeblogger().getUserManager().saveUser(user); + TestUtils.endSession(true); + + setProperty("users.passwords.externalAuthValue", ""); + setProperty("users.passwords.externalAuthValue.previous", ","); + + assertThrows(AuthenticationException.class, () -> provider.authenticate( + new UsernamePasswordAuthenticationToken(userName, ""))); + } + + @Test + void aPreviousUnencodedPlaceholderIsNotAPasswordAfterTheSettingChanges() throws Exception { + setProperty("authentication.method", "ldap"); + setProperty("users.passwords.externalAuthValue", ""); + setProperty("users.passwords.externalAuthValue.previous", "{noop}secret"); + DaoAuthenticationProvider provider = provider(); + // as CustomUserRegistry stored it before the setting changed + User user = TestUtils.setupUser("oldldapuser"); + userName = user.getUserName(); + user.setPassword("{noop}secret"); + WebloggerFactory.getWeblogger().getUserManager().saveUser(user); + TestUtils.endSession(true); + + assertThrows(AuthenticationException.class, () -> provider.authenticate( + new UsernamePasswordAuthenticationToken(userName, "secret"))); + } + + @Test + void emptyEntriesInThePreviousPlaceholdersAreIgnored() throws Exception { + setProperty("users.passwords.externalAuthValue.previous", ",, ,"); + + assertTrue(ExternalLoginAwarePasswordEncoder.isExternalLoginMarker("")); + assertFalse(ExternalLoginAwarePasswordEncoder.isExternalLoginMarker("")); + assertFalse(ExternalLoginAwarePasswordEncoder.isExternalLoginMarker(" ")); + } + @Test void anEmptyConfiguredPlaceholderIsNotAPassword() throws Exception { setProperty("authentication.method", "db"); From c2b9d2d340a60f6ff2313c11a25566171331e495 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Thu, 19 Nov 2026 17:42:02 -0700 Subject: [PATCH 11/25] End a login whose account was disabled before it opened a Roller page A login that recorded its password but had no Roller session yet, because it had not opened a Roller page or its session was passivated, kept going after its account was disabled or removed, since the user lookup came back empty and the check was skipped. Such a session now ends when its recorded account no longer resolves to an enabled user. --- .../weblogger/ui/core/RollerSession.java | 6 ++- .../ui/core/PasswordChangeSessionTest.java | 39 +++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java index 31db01ef12..28d5da909a 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java @@ -146,8 +146,12 @@ private static RollerSession getRollerSession(HttpServletRequest request, HttpSe } rollerSession.setAuthenticatedUser(user); rememberLoginPassword(session, rollerSession); + } else if (session.getAttribute(LOGIN_PASSWORD) != null) { + // the account this login was recorded for has been + // disabled or removed since + return endSession(request, session); } - + } catch (WebloggerException e) { log.error("ERROR: getting user object",e); } diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java index 99c8711b51..f32eb4f944 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java @@ -386,6 +386,45 @@ void passwordChangeEndsAnOpenIdLoginThatHasNotOpenedTheUiYet() throws Exception b.assertLoggedOut(); } + @Test + void disablingAUserEndsALoginThatHasNotOpenedTheUiYet() throws Exception { + Browser admin = new Browser(adminName); + Browser b = new Browser(userName); + admin.request(); + TestUtils.endSession(true); + + saveAsAdmin(admin, bean -> bean.setEnabled(false)); + + b.assertLoggedOut(); + admin.assertLoggedIn(adminName); + } + + @Test + void disablingAUserEndsASessionThatWasPassivated() throws Exception { + Browser admin = new Browser(adminName); + Browser b = new Browser(userName); + admin.request(); + b.request(); + TestUtils.endSession(true); + b.passivate(); + + saveAsAdmin(admin, bean -> bean.setEnabled(false)); + + b.assertLoggedOut(); + } + + @Test + void removingAUserEndsALoginThatHasNotOpenedTheUiYet() throws Exception { + String goneName = TestUtils.setupUser("sessiongone").getUserName(); + TestUtils.endSession(true); + Browser b = new Browser(goneName); + + TestUtils.teardownUser(goneName); + TestUtils.endSession(true); + + b.assertLoggedOut(); + } + @Test void loggingInAgainInAStaleSessionStaysLoggedIn() throws Exception { Browser a = new Browser(userName); From 0869230b386aaeb743676eb8668e39d2361edb28 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Fri, 20 Nov 2026 14:00:36 -0700 Subject: [PATCH 12/25] Clear the login from the session's shared security context before ending the session Requests of the same session share one security context. Clearing only the current request's holder left the login in place for a parallel request, which could then start a new session with the user attached. The test fails without the change. --- .../weblogger/ui/core/RollerSession.java | 4 ++ .../ui/core/PasswordChangeSessionTest.java | 43 +++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java index 28d5da909a..0f2a56aeed 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java @@ -273,6 +273,10 @@ private static boolean isInvalidated(HttpSession session) { */ private static RollerSession endSession(HttpServletRequest request, HttpSession session) { log.info("Ending session of a user whose password or account changed"); + // The session's other requests share this security context, so clear + // the login from it before the session ends; otherwise one of them + // could carry the login into a new session. + SecurityContextHolder.getContext().setAuthentication(null); try { session.invalidate(); } catch (IllegalStateException ignored) { diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java index f32eb4f944..d0c7846727 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java @@ -44,6 +44,7 @@ import org.junit.jupiter.api.Test; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @@ -464,6 +465,35 @@ void requestOnASessionEndedByAnotherRequestIsLoggedOut() throws Exception { b.assertLoggedOut(); } + @Test + void endingASessionLogsOutItsParallelRequests() throws Exception { + Browser a = new Browser(userName); + Browser b = new Browser(userName); + a.request(); + b.request(); + TestUtils.endSession(true); + + changeOwnPassword(a); + + // Spring gives two requests of b the login context kept in b's session + SecurityContext shared = SecurityContextHolder.createEmptyContext(); + shared.setAuthentication(b.login); + HttpServletRequest parallel = b.requestWith(shared); + + // the first one ends the session + SecurityContextHolder.setContext(shared); + RollerSession.getRollerSession(b.httpRequest); + + // the second one asks for a session afterwards, as LoadSaltFilter does + SecurityContextHolder.setContext(shared); + parallel.getSession(true); + RollerSession rollerSession = RollerSession.getRollerSession(parallel); + + assertNull(rollerSession.getAuthenticatedUser(), "the parallel request should have no user"); + assertNull(shared.getAuthentication(), "the login should be cleared for every request of the session"); + a.assertLoggedIn(userName); + } + @Test void savingAProfileOnASessionEndedByAnotherRequestDoesNotFail() throws Exception { Browser b = new Browser(userName); @@ -664,6 +694,19 @@ Authentication accept() { }.accept(); } + /** + * Another request of this browser, which reads its login from the + * given security context, as Spring's request wrapper does. + */ + HttpServletRequest requestWith(SecurityContext context) { + HttpServletRequest other = mock(HttpServletRequest.class); + when(other.getUserPrincipal()).thenAnswer(call -> context.getAuthentication()); + when(other.getSession(false)).thenAnswer(call -> httpRequest.getSession(false)); + when(other.getSession(true)).thenAnswer(call -> httpRequest.getSession(true)); + when(other.getSession()).thenAnswer(call -> httpRequest.getSession(true)); + return other; + } + /** * Another request of this browser ends the session just after the * next request has picked it up. From 1b0bd5edfd5aaafe86a5cf6e50a88590278f8d1e Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Fri, 20 Nov 2026 14:01:51 -0700 Subject: [PATCH 13/25] Refuse a password that BCrypt treats as equal to an external-login marker BCrypt gives some passwords other than a marker the same hash as the marker, so an exact comparison with the marker isn't enough to keep it from matching. After the delegate matches, the encoder now also checks whether the current, default or a previous marker matches the stored value, and refuses the password if one does. The marker list is read once per check. --- .../ExternalLoginAwarePasswordEncoder.java | 50 +++++++++++++------ .../ui/core/ExternalLoginPlaceholderTest.java | 20 ++++++++ 2 files changed, 56 insertions(+), 14 deletions(-) diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java index 1c0e0bf7bc..aa87e3ce9c 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java @@ -17,6 +17,9 @@ package org.apache.roller.weblogger.ui.core.security; +import java.util.LinkedHashSet; +import java.util.Set; + import org.apache.commons.lang3.StringUtils; import org.apache.roller.weblogger.config.WebloggerConfig; import org.springframework.security.crypto.password.PasswordEncoder; @@ -25,7 +28,8 @@ * Users who log in through LDAP or the servlet container have no Roller * password; Roller stores users.passwords.externalAuthValue in its place. * That placeholder is not a password, so this encoder never matches it, nor - * the default or a previous placeholder, nor an empty password. + * the default or a previous placeholder, nor a password the delegate treats + * as equal to one of them, nor an empty password. */ public class ExternalLoginAwarePasswordEncoder implements PasswordEncoder { @@ -55,22 +59,27 @@ public static String externalLoginMarker() { * them matches at login, so none can be chosen as a Roller password. */ public static boolean isExternalLoginMarker(CharSequence password) { - if (password == null) { - return false; - } - if (externalLoginMarker().contentEquals(password) - || DEFAULT_EXTERNAL_LOGIN_MARKER.contentEquals(password)) { - return true; - } + return password != null && externalLoginMarkers().contains(password.toString()); + } + + /** + * The configured marker, the default one and the previous ones. The + * previous ones are a comma-separated list, so a marker that contains a + * comma can't be listed there. + */ + private static Set externalLoginMarkers() { + Set markers = new LinkedHashSet<>(); + markers.add(externalLoginMarker()); + markers.add(DEFAULT_EXTERNAL_LOGIN_MARKER); String previous = WebloggerConfig.getProperty("users.passwords.externalAuthValue.previous"); for (String marker : StringUtils.split(StringUtils.defaultString(previous), ',')) { // an empty entry is never a marker, so an empty password isn't one String trimmed = marker.trim(); - if (!trimmed.isEmpty() && trimmed.contentEquals(password)) { - return true; + if (!trimmed.isEmpty()) { + markers.add(trimmed); } } - return false; + return markers; } @Override @@ -80,13 +89,26 @@ public String encode(CharSequence rawPassword) { @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { + if (rawPassword == null || rawPassword.length() == 0) { + return false; + } + Set markers = externalLoginMarkers(); // a stored marker is checked before the delegate sees it, since a // marker such as {noop}secret would otherwise match its own suffix - if (rawPassword == null || rawPassword.length() == 0 || isExternalLoginMarker(rawPassword) - || isExternalLoginMarker(encodedPassword)) { + if (markers.contains(encodedPassword) || markers.contains(rawPassword.toString())) { return false; } - return delegate.matches(rawPassword, encodedPassword); + if (!delegate.matches(rawPassword, encodedPassword)) { + return false; + } + // BCrypt, for one, treats some other passwords as equal to a marker, + // so refuse any password whose stored value a marker matches too + for (String marker : markers) { + if (delegate.matches(marker, encodedPassword)) { + return false; + } + } + return true; } @Override diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java index 6443498bc6..970cf8dda8 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java @@ -41,6 +41,8 @@ import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.context.WebApplicationContext; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -276,6 +278,24 @@ String sign() { } } + @Test + void aPasswordThatBcryptTreatsAsEqualToThePlaceholderNeverMatches() throws Exception { + setProperty("users.passwords.externalAuthValue", ""); + setProperty("users.passwords.externalAuthValue.previous", ""); + provider(); + PasswordEncoder encoder = RollerContext.getPasswordEncoder(); + for (String marker : new String[] {"", "", ""}) { + String stored = encoder.encode(marker); + // BCrypt repeats its key, a NUL byte after each copy, so this + // password gives the same hash as the placeholder + String sameKey = marker + '\0' + marker; + assertTrue(new BCryptPasswordEncoder().matches(sameKey, stored.substring("{bcrypt}".length()))); + assertFalse(encoder.matches(sameKey, stored), marker); + } + // a password that only starts like a placeholder still matches + assertTrue(encoder.matches("x", encoder.encode("x"))); + } + /** The login form's provider, given its encoder the way RollerContext does at startup. */ private static DaoAuthenticationProvider provider() { DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); From b1318fb8af1358e3c0ac26b1b76989b4e93ebe9c Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Fri, 20 Nov 2026 14:01:57 -0700 Subject: [PATCH 14/25] Send a request whose session was just ended back to its page or to the login page A request whose session ended because its user's password or account changed went on with no user, so a page showed Access Denied and a form post failed the salt check with a server error. The salt filters now redirect it: a page request goes back to the same page, where Spring Security asks for a login if the page needs one, and a form post goes to the login page. Weblog pages forwarded through the filter still render for a visitor who is not logged in. --- .../weblogger/ui/core/RollerSession.java | 12 +++++ .../ui/core/filters/LoadSaltFilter.java | 31 +++++++++++ .../ui/core/filters/ValidateSaltFilter.java | 4 ++ .../ui/core/PasswordChangeSessionTest.java | 9 ++++ .../ui/core/filters/LoadSaltFilterTest.java | 52 +++++++++++++++++++ .../core/filters/ValidateSaltFilterTest.java | 23 ++++++++ 6 files changed, 131 insertions(+) diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java index 0f2a56aeed..049fd4da18 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java @@ -63,6 +63,9 @@ public class RollerSession // session so they outlive it when the container passivates the session private static final String LOGIN_PASSWORD = ROLLER_SESSION + ".login"; + // request attribute that marks a request whose session was ended + private static final String SESSION_ENDED = ROLLER_SESSION + ".ended"; + static{ WebloggerConfig.init(); // must be called before calls to logging APIs log = LogFactory.getLog(RollerSession.class); @@ -283,6 +286,7 @@ private static RollerSession endSession(HttpServletRequest request, HttpSession // already invalidated } SecurityContextHolder.clearContext(); + request.setAttribute(SESSION_ENDED, Boolean.TRUE); RollerSession rollerSession = new RollerSession(); try { request.getSession(true).setAttribute(ROLLER_SESSION, rollerSession); @@ -293,6 +297,14 @@ private static RollerSession endSession(HttpServletRequest request, HttpSession return rollerSession; } + /** + * Whether this request's session was ended because its login no longer + * holds, so the request now has no user. + */ + public static boolean isSessionEnded(HttpServletRequest request) { + return request.getAttribute(SESSION_ENDED) != null; + } + /** Digest of the stored password hash, so the session does not hold it. */ private static String digest(User user) { String password = user.getPassword() != null ? user.getPassword() : ""; diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilter.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilter.java index 8a1c830fa3..d3c1687879 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilter.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilter.java @@ -22,6 +22,7 @@ import java.security.SecureRandom; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.RandomStringUtils; import org.apache.roller.weblogger.ui.core.RollerSession; import org.apache.roller.weblogger.ui.rendering.util.cache.SaltCache; @@ -39,6 +40,9 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha HttpServletRequest httpReq = (HttpServletRequest) request; httpReq.getSession(true); RollerSession rollerSession = RollerSession.getRollerSession(httpReq); + if (redirectEndedSession(httpReq, (HttpServletResponse) response)) { + return; + } if (rollerSession != null) { String userId = rollerSession.getAuthenticatedUser() != null ? rollerSession.getAuthenticatedUser().getId() : ""; SaltCache saltCache = SaltCache.getInstance(); @@ -50,6 +54,33 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha chain.doFilter(request, response); } + /** + * Sends a request whose session Roller has just ended, because its user's + * password or account changed, back to the page it asked for, or to the + * login page if it posted a form. Spring Security then asks for a login + * where one is needed, as it does for any visitor who is not logged in. + * A weblog page forwarded here renders for a visitor who is not logged in. + * + * @return true when the request was redirected + */ + static boolean redirectEndedSession(HttpServletRequest request, HttpServletResponse response) + throws IOException { + if (!RollerSession.isSessionEnded(request) + || request.getDispatcherType() != DispatcherType.REQUEST) { + return false; + } + String target; + if ("GET".equalsIgnoreCase(request.getMethod()) || "HEAD".equalsIgnoreCase(request.getMethod())) { + target = request.getContextPath() + request.getServletPath() + + (request.getPathInfo() != null ? request.getPathInfo() : "") + + (request.getQueryString() != null ? "?" + request.getQueryString() : ""); + } else { + target = request.getContextPath() + "/roller-ui/login.rol"; + } + response.sendRedirect(target); + return true; + } + @Override public void init(FilterConfig filterConfig) throws ServletException { } diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/filters/ValidateSaltFilter.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/filters/ValidateSaltFilter.java index c0aa87f340..7b0f322af7 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/filters/ValidateSaltFilter.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/filters/ValidateSaltFilter.java @@ -62,6 +62,10 @@ public void doFilter(ServletRequest request, ServletResponse response, try { SaltValidator.requireSubmittedSalt(httpReq); } catch (ServletException e) { + // the salt was issued to a login whose session just ended + if (LoadSaltFilter.redirectEndedSession(httpReq, (HttpServletResponse) response)) { + return; + } if (isPostTooLarge(httpReq)) { // The container dropped the form, salt included, because it // is over its maximum POST size. Pasted images make this diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java index d0c7846727..812d575059 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java @@ -626,6 +626,8 @@ private static final class Browser { boolean ended; // a session another request invalidated after this one picked it up HttpSession endedUnderneath; + // attributes of the current request + final Map requestAttributes = new HashMap<>(); Browser(String name) { this(UsernamePasswordAuthenticationToken.authenticated(name, null, List.of())); @@ -654,6 +656,10 @@ private Browser(Authentication authentication, boolean remembered) { return session; }); when(httpRequest.getSession()).thenAnswer(call -> httpRequest.getSession(true)); + doAnswer(call -> requestAttributes.put(call.getArgument(0), call.getArgument(1))) + .when(httpRequest).setAttribute(anyString(), any()); + when(httpRequest.getAttribute(anyString())) + .thenAnswer(call -> requestAttributes.get(call.getArgument(0))); if (remembered) { rememberMeLogin(authentication.getName()); } else { @@ -764,6 +770,7 @@ void passivate() { } RollerSession request() { + requestAttributes.clear(); if (ended && endedUnderneath == null) { SecurityContextHolder.clearContext(); } else { @@ -777,6 +784,7 @@ void assertLoggedOut() { assertNull(rollerSession == null ? null : rollerSession.getAuthenticatedUser(), "the session should no longer have a user"); assertTrue(ended, "the HTTP session should be invalidated"); + assertTrue(RollerSession.isSessionEnded(httpRequest), "the request should be marked as logged out"); assertNull(SecurityContextHolder.getContext().getAuthentication(), "the login should be cleared from this request"); SecurityContextHolder.clearContext(); @@ -788,6 +796,7 @@ void assertLoggedIn(String name) { assertNotNull(rollerSession.getAuthenticatedUser(), "the session should keep its user"); assertEquals(name, rollerSession.getAuthenticatedUser().getUserName()); assertFalse(ended, "the HTTP session should stay valid"); + assertFalse(RollerSession.isSessionEnded(httpRequest)); assertNotNull(SecurityContextHolder.getContext().getAuthentication()); SecurityContextHolder.clearContext(); } diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilterTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilterTest.java index 2087a005b3..2430d07e3b 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilterTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilterTest.java @@ -9,6 +9,7 @@ import org.mockito.MockedStatic; import org.mockito.MockitoAnnotations; +import javax.servlet.DispatcherType; import javax.servlet.FilterChain; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -74,6 +75,57 @@ public void testDoFilterWithNullRollerSession() throws Exception { } } + @Test + void requestWhoseSessionWasEndedGoesBackToThePageItAskedFor() throws Exception { + try (MockedStatic mockedRollerSession = mockStatic(RollerSession.class)) { + mockedRollerSession.when(() -> RollerSession.getRollerSession(request)).thenReturn(rollerSession); + mockedRollerSession.when(() -> RollerSession.isSessionEnded(request)).thenReturn(true); + when(request.getDispatcherType()).thenReturn(DispatcherType.REQUEST); + when(request.getMethod()).thenReturn("GET"); + when(request.getContextPath()).thenReturn("/roller"); + when(request.getServletPath()).thenReturn("/roller-ui/menu.rol"); + when(request.getQueryString()).thenReturn("weblog=demo"); + + filter.doFilter(request, response, chain); + + verify(response).sendRedirect("/roller/roller-ui/menu.rol?weblog=demo"); + verify(chain, never()).doFilter(request, response); + } + } + + @Test + void formPostWhoseSessionWasEndedGoesToTheLoginPage() throws Exception { + try (MockedStatic mockedRollerSession = mockStatic(RollerSession.class)) { + mockedRollerSession.when(() -> RollerSession.getRollerSession(request)).thenReturn(rollerSession); + mockedRollerSession.when(() -> RollerSession.isSessionEnded(request)).thenReturn(true); + when(request.getDispatcherType()).thenReturn(DispatcherType.REQUEST); + when(request.getMethod()).thenReturn("POST"); + when(request.getContextPath()).thenReturn("/roller"); + + filter.doFilter(request, response, chain); + + verify(response).sendRedirect("/roller/roller-ui/login.rol"); + verify(chain, never()).doFilter(request, response); + } + } + + @Test + void weblogPageWhoseSessionWasEndedStillRenders() throws Exception { + try (MockedStatic mockedRollerSession = mockStatic(RollerSession.class); + MockedStatic mockedSaltCache = mockStatic(SaltCache.class)) { + mockedRollerSession.when(() -> RollerSession.getRollerSession(request)).thenReturn(rollerSession); + mockedRollerSession.when(() -> RollerSession.isSessionEnded(request)).thenReturn(true); + mockedSaltCache.when(SaltCache::getInstance).thenReturn(saltCache); + // weblog pages are forwarded to the rendering servlets + when(request.getDispatcherType()).thenReturn(DispatcherType.FORWARD); + + filter.doFilter(request, response, chain); + + verify(response, never()).sendRedirect(anyString()); + verify(chain).doFilter(request, response); + } + } + @Test void firstFormHasAUsableSalt() throws Exception { javax.servlet.http.HttpSession session = mock(javax.servlet.http.HttpSession.class); diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/ValidateSaltFilterTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/ValidateSaltFilterTest.java index f312ffc0c1..3986772903 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/ValidateSaltFilterTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/ValidateSaltFilterTest.java @@ -9,6 +9,7 @@ import org.mockito.MockedStatic; import org.mockito.MockitoAnnotations; +import javax.servlet.DispatcherType; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; @@ -87,6 +88,28 @@ public void testDoFilterWithPostMethodAndInvalidSalt() throws Exception { } } + @Test + void formPostWhoseSessionWasEndedGoesToTheLoginPage() throws Exception { + try (MockedStatic mockedRollerSession = mockStatic(RollerSession.class); + MockedStatic mockedSaltCache = mockStatic(SaltCache.class)) { + + // the session ended, so the form's salt belongs to its old user + mockedRollerSession.when(() -> RollerSession.getRollerSession(request)).thenReturn(rollerSession); + mockedRollerSession.when(() -> RollerSession.isSessionEnded(request)).thenReturn(true); + mockedSaltCache.when(SaltCache::getInstance).thenReturn(saltCache); + when(request.getDispatcherType()).thenReturn(DispatcherType.REQUEST); + when(request.getMethod()).thenReturn("POST"); + when(request.getContextPath()).thenReturn("/roller"); + when(request.getParameter("salt")).thenReturn("oldSalt"); + when(saltCache.get("oldSalt")).thenReturn("userId"); + + filter.doFilter(request, response, chain); + + verify(response).sendRedirect("/roller/roller-ui/login.rol"); + verify(chain, never()).doFilter(request, response); + } + } + @Test public void testPostTooLargeForTheContainerGetsA413() throws Exception { try (MockedStatic mockedRollerSession = mockStatic(RollerSession.class)) { From d2beeaf4438f982e8d366adcf55cdd82c0ccc7e2 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Fri, 20 Nov 2026 14:02:53 -0700 Subject: [PATCH 15/25] Don't pass a missing or empty stored password to the delegate encoder DelegatingPasswordEncoder throws for a stored value without an encoder prefix when no lazy-upgrade encoder is configured, and for a null value, so such an account ended the login with an exception instead of bad credentials. The encoder now answers false for them. --- .../core/security/ExternalLoginAwarePasswordEncoder.java | 4 +++- .../weblogger/ui/core/ExternalLoginPlaceholderTest.java | 9 +++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java index aa87e3ce9c..c25b94146e 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java @@ -89,7 +89,9 @@ public String encode(CharSequence rawPassword) { @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { - if (rawPassword == null || rawPassword.length() == 0) { + // the delegate can throw for a missing or empty stored value + if (rawPassword == null || rawPassword.length() == 0 + || encodedPassword == null || encodedPassword.isEmpty()) { return false; } Set markers = externalLoginMarkers(); diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java index 970cf8dda8..fbdae348fd 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java @@ -296,6 +296,15 @@ void aPasswordThatBcryptTreatsAsEqualToThePlaceholderNeverMatches() throws Excep assertTrue(encoder.matches("x", encoder.encode("x"))); } + @Test + void anEmptyOrMissingStoredPasswordDoesNotMatch() throws Exception { + setProperty("passwds.encryption.lazyUpgradeFrom", ""); + provider(); + PasswordEncoder encoder = RollerContext.getPasswordEncoder(); + assertFalse(encoder.matches("secret", "")); + assertFalse(encoder.matches("secret", null)); + } + /** The login form's provider, given its encoder the way RollerContext does at startup. */ private static DaoAuthenticationProvider provider() { DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); From ab7676515e3b01fecbf7c0db3d9220a40108eee3 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Fri, 20 Nov 2026 14:03:14 -0700 Subject: [PATCH 16/25] Log when a password is refused as an external-login marker An account whose real password equals the current, default or a previous marker can't log in, and until now the log didn't say why. The encoder now logs an info line for that refusal, without the password, so an administrator can tell it from a wrong password and set a new one. --- .../ExternalLoginAwarePasswordEncoder.java | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java index c25b94146e..965b79e019 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java @@ -21,6 +21,8 @@ import java.util.Set; 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.springframework.security.crypto.password.PasswordEncoder; @@ -33,6 +35,8 @@ */ public class ExternalLoginAwarePasswordEncoder implements PasswordEncoder { + private static final Log log = LogFactory.getLog(ExternalLoginAwarePasswordEncoder.class); + /** Stored in place of a password when no other value is configured. */ public static final String DEFAULT_EXTERNAL_LOGIN_MARKER = ""; @@ -97,7 +101,11 @@ public boolean matches(CharSequence rawPassword, String encodedPassword) { Set markers = externalLoginMarkers(); // a stored marker is checked before the delegate sees it, since a // marker such as {noop}secret would otherwise match its own suffix - if (markers.contains(encodedPassword) || markers.contains(rawPassword.toString())) { + if (markers.contains(encodedPassword)) { + return false; + } + if (markers.contains(rawPassword.toString())) { + logRefusal(); return false; } if (!delegate.matches(rawPassword, encodedPassword)) { @@ -107,12 +115,20 @@ public boolean matches(CharSequence rawPassword, String encodedPassword) { // so refuse any password whose stored value a marker matches too for (String marker : markers) { if (delegate.matches(marker, encodedPassword)) { + logRefusal(); return false; } } return true; } + private static void logRefusal() { + // the password itself is never logged + log.info("Refused a password that Roller treats as an external-login marker" + + " (users.passwords.externalAuthValue or its .previous list). An" + + " administrator can set a new password for an account that uses one."); + } + @Override public boolean upgradeEncoding(String encodedPassword) { return delegate.upgradeEncoding(encodedPassword); From c8347ce5d0e902be305db23c4cda0600604c7946 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Fri, 20 Nov 2026 14:03:14 -0700 Subject: [PATCH 17/25] Document the limits of users.passwords.externalAuthValue.previous The list is comma-separated, so a marker that contains a comma can't be listed there. roller.properties now says so, along with the accounts that need an administrator to set a new password. Roller also logs a warning at startup when the configured marker contains a comma. --- .../ui/core/security/ExternalLoginAwarePasswordEncoder.java | 4 ++++ .../org/apache/roller/weblogger/config/roller.properties | 4 +++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java index 965b79e019..6bf9cc9dd4 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/ExternalLoginAwarePasswordEncoder.java @@ -44,6 +44,10 @@ public class ExternalLoginAwarePasswordEncoder implements PasswordEncoder { public ExternalLoginAwarePasswordEncoder(PasswordEncoder delegate) { this.delegate = delegate; + if (externalLoginMarker().contains(",")) { + log.warn("users.passwords.externalAuthValue contains a comma, so it can't be listed in" + + " users.passwords.externalAuthValue.previous if the setting changes later."); + } } /** diff --git a/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties b/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties index 074a930cc6..f165134ae6 100644 --- a/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties +++ b/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties @@ -366,7 +366,9 @@ users.passwords.externalAuthValue= # Comma-separated values that users.passwords.externalAuthValue had before. # Accounts created then still have them stored, so list them here when changing -# that setting; none of them is accepted as a password. +# that setting; none of them is accepted as a password. A value that contains +# a comma can't be listed, and an account whose own password is one of them +# needs an administrator to set a new password. users.passwords.externalAuthValue.previous= # Password security settings From 3181960d075108fcf25399c01e6a2df0ef8e08c1 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Fri, 20 Nov 2026 14:04:28 -0700 Subject: [PATCH 18/25] Keep a session's own requests logged in while it saves a new password Between the commit of a new password and the update of the saving session, another request of the same session saw the new password and ended the session. The saving request now tells its session which password it is storing first, and the session takes that password on as soon as it is stored. The user's other sessions still end. --- .../weblogger/ui/core/RollerSession.java | 46 +++++++++++++++++-- .../weblogger/ui/struts2/admin/UserEdit.java | 3 ++ .../weblogger/ui/struts2/core/Profile.java | 3 +- .../ui/core/PasswordChangeSessionTest.java | 24 ++++++++++ 4 files changed, 71 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java index 049fd4da18..6b63b9c7bd 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java @@ -54,6 +54,9 @@ public class RollerSession // digest of the user's stored password hash when this session logged in private String passwordDigest = null; + + // digest of a password hash this session's own request is saving + private volatile String savingPasswordDigest = null; private static final Log log; @@ -103,7 +106,7 @@ private static RollerSession getRollerSession(HttpServletRequest request, HttpSe // password also logs out the user's other browsers. This runs // before the cache check below, which rebuilds the session // from the login and would take on the new password. - if (!rollerSession.isCurrent()) { + if (!rollerSession.isCurrent(session)) { return endSession(request, session); } // Check if session is still valid in cache @@ -200,6 +203,30 @@ public static void loggedIn(HttpServletRequest request, Principal login) { } } + /** + * Keeps the current session's other requests logged in while it saves a + * new password for its own user. Call it before the new password is + * saved, and refreshPassword after. + */ + public static void savingPassword(HttpServletRequest request, User user) { + HttpSession session = request != null ? request.getSession(false) : null; + if (session == null || user == null) { + return; + } + try { + Object attribute = session.getAttribute(ROLLER_SESSION); + if (attribute instanceof RollerSession + && user.getUserName().equals(((RollerSession) attribute).userName)) { + ((RollerSession) attribute).savingPasswordDigest = digest(user); + } + } catch (IllegalStateException e) { + if (!isInvalidated(session)) { + throw e; + } + // another request ended the session, there is no login to keep + } + } + /** * Keeps the current session logged in after its own user changed their * password, or an administrator changed their own. Call it after the new @@ -215,6 +242,7 @@ public static void refreshPassword(HttpServletRequest request, User user) { if (attribute instanceof RollerSession && user.getUserName().equals(((RollerSession) attribute).userName)) { ((RollerSession) attribute).setAuthenticatedUser(user); + ((RollerSession) attribute).savingPasswordDigest = null; rememberLoginPassword(session, (RollerSession) attribute); } } catch (IllegalStateException e) { @@ -245,9 +273,10 @@ private static void rememberLoginPassword(HttpSession session, RollerSession rol /** * Whether the user this session logged in as is still enabled and still * has the password the session logged in with. A failed lookup keeps the - * session, so a database error does not log everyone out. + * session, so a database error does not log everyone out. A session that + * is saving a new password for its user takes it on once it is stored. */ - private boolean isCurrent() { + private boolean isCurrent(HttpSession session) { User user; try { UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); @@ -257,7 +286,16 @@ private boolean isCurrent() { log.warn("Error looking up authenticated user " + userName, ex); return true; } - return user != null && digest(user).equals(passwordDigest); + if (user == null) { + return false; + } + String current = digest(user); + if (current.equals(savingPasswordDigest)) { + passwordDigest = current; + savingPasswordDigest = null; + rememberLoginPassword(session, this); + } + return current.equals(passwordDigest); } private static boolean isInvalidated(HttpSession session) { diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/admin/UserEdit.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/admin/UserEdit.java index 0cf413d43c..97ca1973bb 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/admin/UserEdit.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/admin/UserEdit.java @@ -202,6 +202,9 @@ public String save() { // save new user mgr.addUser(user); } else { + if (isUserEditingSelf()) { + RollerSession.savingPassword(getServletRequest(), user); + } mgr.saveUser(user); } diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Profile.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Profile.java index fb80918466..d3c5c918f7 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Profile.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Profile.java @@ -132,10 +132,11 @@ public String save() { try { // save the updated profile + // a password change ends the user's other sessions, not this one + RollerSession.savingPassword(getServletRequest(), existingUser); UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); mgr.saveUser(existingUser); WebloggerFactory.getWeblogger().flush(); - // a password change ends the user's other sessions, not this one RollerSession.refreshPassword(getServletRequest(), existingUser); addMessage("generic.changes.saved"); return SUCCESS; diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java index 812d575059..f51aa33b86 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java @@ -494,6 +494,30 @@ void endingASessionLogsOutItsParallelRequests() throws Exception { a.assertLoggedIn(userName); } + @Test + void ownRequestWhilePasswordIsSavedStaysLoggedIn() throws Exception { + Browser a = new Browser(userName); + Browser b = new Browser(userName); + a.request(); + b.request(); + TestUtils.endSession(true); + + // what Profile.save does, with another request of a in between the + // commit and the end of the save + a.request(); + User self = user(userName); + self.resetPassword("changed-password"); + RollerSession.savingPassword(a.httpRequest, self); + WebloggerFactory.getWeblogger().getUserManager().saveUser(self); + WebloggerFactory.getWeblogger().flush(); + a.assertLoggedIn(userName); + RollerSession.refreshPassword(a.httpRequest, self); + TestUtils.endSession(true); + + a.assertLoggedIn(userName); + b.assertLoggedOut(); + } + @Test void savingAProfileOnASessionEndedByAnotherRequestDoesNotFail() throws Exception { Browser b = new Browser(userName); From bfb437148aa2ff550501678fb4887763471c0364 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Fri, 20 Nov 2026 14:05:08 -0700 Subject: [PATCH 19/25] Test previous external-login markers in the password forms and the encoder ExternalLoginMarkerPasswordTest now checks that registration, the profile page and user administration refuse a marker listed in users.passwords.externalAuthValue.previous, and its tearDown restores the configuration in a finally block. The provider tests for previous markers also check the encoder directly, and the list test covers spaces around an entry. --- .../ui/core/ExternalLoginPlaceholderTest.java | 5 +- .../core/ExternalLoginMarkerPasswordTest.java | 57 ++++++++++++++++--- 2 files changed, 53 insertions(+), 9 deletions(-) diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java index fbdae348fd..e93592900c 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/ExternalLoginPlaceholderTest.java @@ -163,6 +163,7 @@ void aPreviousEncodedPlaceholderIsNotAPasswordAfterTheSettingChanges() throws Ex assertThrows(AuthenticationException.class, () -> provider.authenticate( new UsernamePasswordAuthenticationToken(userName, ""))); + assertFalse(RollerContext.getPasswordEncoder().matches("", user.getPassword())); } @Test @@ -180,12 +181,14 @@ void aPreviousUnencodedPlaceholderIsNotAPasswordAfterTheSettingChanges() throws assertThrows(AuthenticationException.class, () -> provider.authenticate( new UsernamePasswordAuthenticationToken(userName, "secret"))); + assertFalse(RollerContext.getPasswordEncoder().matches("secret", "{noop}secret")); } @Test void emptyEntriesInThePreviousPlaceholdersAreIgnored() throws Exception { - setProperty("users.passwords.externalAuthValue.previous", ",, ,"); + setProperty("users.passwords.externalAuthValue.previous", ", ,, ,"); + assertTrue(ExternalLoginAwarePasswordEncoder.isExternalLoginMarker("")); assertTrue(ExternalLoginAwarePasswordEncoder.isExternalLoginMarker("")); assertFalse(ExternalLoginAwarePasswordEncoder.isExternalLoginMarker("")); assertFalse(ExternalLoginAwarePasswordEncoder.isExternalLoginMarker(" ")); diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/ExternalLoginMarkerPasswordTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/ExternalLoginMarkerPasswordTest.java index 3d9389e6f5..f7b436232d 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/ExternalLoginMarkerPasswordTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/ExternalLoginMarkerPasswordTest.java @@ -75,15 +75,20 @@ void setUp() throws Exception { @AfterEach void tearDown() throws Exception { - factory.close(); - Properties config = config(); - savedProperties.forEach((k, v) -> { - if (v == null) { - config.remove(k); - } else { - config.setProperty(k, v); + try { + if (factory != null) { + factory.close(); } - }); + } finally { + Properties config = config(); + savedProperties.forEach((k, v) -> { + if (v == null) { + config.remove(k); + } else { + config.setProperty(k, v); + } + }); + } } @Test @@ -192,6 +197,42 @@ void anAdministratorCannotCreateAUserWithTheMarker() throws Exception { verify(users, never()).addUser(any()); } + @Test + void theFormsRejectAPreviousMarker() throws Exception { + setProperty("users.passwords.externalAuthValue.previous", ", "); + + Register register = withText(new Register()); + register.getBean().setUserName("newuser"); + register.getBean().setPasswordText(""); + register.getBean().setPasswordConfirm(""); + register.myValidate(); + assertTrue(register.getActionErrors().contains(RESERVED)); + + User user = new User(); + user.setUserName("dbuser"); + user.setPassword("{bcrypt}existing"); + Profile profile = withText(new Profile()); + profile.setAuthenticatedUser(user); + profile.getBean().setPasswordText(""); + profile.getBean().setPasswordConfirm(""); + assertEquals(UIAction.INPUT, profile.save()); + assertTrue(profile.getActionErrors().contains(RESERVED)); + + User admin = new User(); + admin.setUserName("admin"); + UserEdit userEdit = withText(new UserEdit()); + userEdit.setActionName("createUser"); + userEdit.setAuthenticatedUser(admin); + userEdit.myPrepare(); + userEdit.getBean().setUserName("newuser"); + userEdit.getBean().setPassword(""); + assertEquals(UIAction.INPUT, userEdit.save()); + assertTrue(userEdit.getActionErrors().contains(RESERVED)); + + verify(users, never()).saveUser(any()); + verify(users, never()).addUser(any()); + } + private static T withText(T action) { T spied = spy(action); doAnswer(call -> call.getArgument(0)).when(spied).getText(anyString()); From b396cb55d08f6306d4f7a13963e3f69932ab0986 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Fri, 20 Nov 2026 14:05:08 -0700 Subject: [PATCH 20/25] Mention users.passwords.externalAuthValue.previous in CHANGES --- CHANGES.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 549a1ff55c..adaa2d4b91 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -84,8 +84,11 @@ - **New passwords can't be the external-login placeholder.** Registration, the profile page and user administration refuse `users.passwords.externalAuthValue` (by default ``) as a - password, and it never works as one. An administrator can set a new password - for an account that used it (#306). + password, and it never works as one. When you change that setting, list its + earlier values in the new `users.passwords.externalAuthValue.previous` + (comma-separated) so they're treated the same. A login refused for this + reason is logged, and an administrator can set a new password for an + account that used one (#306). - **The LDAP comment authenticator escapes the commenter's user name** when it builds the bind name (#334). - **Roller UI stylesheets, scripts and images don't start a session** (#332). From 40b33edcad3b0d39c2bed4209cafc03b096a05fb Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Fri, 20 Nov 2026 14:06:18 -0700 Subject: [PATCH 21/25] Answer comment data requests without a user with 403 instead of a server error A request whose session has no user, such as one whose session was just ended, made the permission check fail with a NullPointerException. --- .../ui/struts2/ajax/CommentDataServlet.java | 13 ++++++-- .../struts2/ajax/CommentDataServletTest.java | 32 +++++++++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/ajax/CommentDataServlet.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/ajax/CommentDataServlet.java index e1fc9d1969..3dfb7b2d02 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/ajax/CommentDataServlet.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/ajax/CommentDataServlet.java @@ -64,7 +64,7 @@ public void doGet(HttpServletRequest request, // need post permission to view comments RollerSession rses = RollerSession.getRollerSession(request); Weblog weblog = c.getWeblogEntry().getWebsite(); - if (weblog.hasUserPermission(rses.getAuthenticatedUser(), WeblogPermission.POST)) { + if (hasPostPermission(rses, weblog)) { // HTML-escaped, since the page shows it as HTML String content = Utilities.escapeHTML(c.getContent()); String json = "{\"id\":\"" + StringEscapeUtils.escapeJson(c.getId()) @@ -105,7 +105,7 @@ public void doPut(HttpServletRequest request, // need post permission to edit comments RollerSession rses = RollerSession.getRollerSession(request); Weblog weblog = c.getWeblogEntry().getWebsite(); - if (weblog.hasUserPermission(rses.getAuthenticatedUser(), WeblogPermission.POST)) { + if (hasPostPermission(rses, weblog)) { String content = Utilities.streamToString(request.getInputStream()); c.setContent(content); // don't update the posttime when updating the comment @@ -137,6 +137,15 @@ public void doPost(HttpServletRequest request, doPut(request, response); } + /** + * Whether the session's user may post to the weblog. A request with no + * user, such as one whose session was just ended, may not. + */ + private static boolean hasPostPermission(RollerSession rses, Weblog weblog) { + return rses != null && rses.getAuthenticatedUser() != null + && weblog.hasUserPermission(rses.getAuthenticatedUser(), WeblogPermission.POST); + } + private void writeSaveResponse(HttpServletRequest request, HttpServletResponse response, int status, String id, String content) throws IOException { diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/ajax/CommentDataServletTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/ajax/CommentDataServletTest.java index 8efda9cefb..91b21f645d 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/ajax/CommentDataServletTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/ajax/CommentDataServletTest.java @@ -94,6 +94,38 @@ public void testGetReturnsJson() throws Exception { json.get("content").asText()); } + @Test + public void testGetWithoutAUserIsForbidden() throws Exception { + Weblogger weblogger = mock(Weblogger.class); + WeblogEntryManager manager = mock(WeblogEntryManager.class); + WeblogEntryComment comment = mock(WeblogEntryComment.class); + WeblogEntry entry = mock(WeblogEntry.class); + Weblog weblog = mock(Weblog.class); + // a session that was just ended has no user + RollerSession session = mock(RollerSession.class); + + when(weblogger.getWeblogEntryManager()).thenReturn(manager); + when(manager.getComment("comment-id")).thenReturn(comment); + when(comment.getWeblogEntry()).thenReturn(entry); + when(entry.getWebsite()).thenReturn(weblog); + // as Weblog does, which builds a permission from the user + when(weblog.hasUserPermission(null, WeblogPermission.POST)).thenThrow(new NullPointerException()); + + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getParameter("id")).thenReturn("comment-id"); + HttpServletResponse response = mock(HttpServletResponse.class); + + try (MockedStatic factory = mockStatic(WebloggerFactory.class); + MockedStatic sessions = mockStatic(RollerSession.class)) { + factory.when(WebloggerFactory::getWeblogger).thenReturn(weblogger); + sessions.when(() -> RollerSession.getRollerSession(request)).thenReturn(session); + + new CommentDataServlet().doGet(request, response); + } + + verify(response).setStatus(HttpServletResponse.SC_FORBIDDEN); + } + @Test public void testRepeatedSavesReturnFreshResponseSalts() throws Exception { Weblogger weblogger = mock(Weblogger.class); From d652d4ce2d6bd3f0ec767ff3f911bbcafea782ba Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Fri, 20 Nov 2026 14:06:18 -0700 Subject: [PATCH 22/25] Name the user and the reason when a session is ended The log line said a password or account had changed even when the request was only following a session another request had ended, and it didn't say whose session it was. --- .../weblogger/ui/core/RollerSession.java | 20 ++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java index 6b63b9c7bd..c7eb936042 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java @@ -87,7 +87,7 @@ public static RollerSession getRollerSession(HttpServletRequest request) { } // another request of the same browser ended the session while // this one was using it, so this one is logged out too - return endSession(request, session); + return endSession(request, session, null); } } @@ -107,7 +107,7 @@ private static RollerSession getRollerSession(HttpServletRequest request, HttpSe // before the cache check below, which rebuilds the session // from the login and would take on the new password. if (!rollerSession.isCurrent(session)) { - return endSession(request, session); + return endSession(request, session, rollerSession.userName); } // Check if session is still valid in cache RollerLoginSessionManager manager = RollerLoginSessionManager.getInstance(); @@ -148,14 +148,14 @@ private static RollerSession getRollerSession(HttpServletRequest request, HttpSe // a login whose password changed since it was first // seen ends here too, even with no Roller session left if (!sameLoginPassword(session, user)) { - return endSession(request, session); + return endSession(request, session, user.getUserName()); } rollerSession.setAuthenticatedUser(user); rememberLoginPassword(session, rollerSession); } else if (session.getAttribute(LOGIN_PASSWORD) != null) { // the account this login was recorded for has been // disabled or removed since - return endSession(request, session); + return endSession(request, session, principal.getName()); } } catch (WebloggerException e) { @@ -310,10 +310,16 @@ private static boolean isInvalidated(HttpSession session) { /** * Ends a session whose login no longer holds: invalidates it, clears the * login from this request, and gives the rest of the request a new - * session with no user, as any visitor who is not logged in gets. + * session with no user, as any visitor who is not logged in gets. The + * user name is null when another request already ended the session. */ - private static RollerSession endSession(HttpServletRequest request, HttpSession session) { - log.info("Ending session of a user whose password or account changed"); + private static RollerSession endSession(HttpServletRequest request, HttpSession session, String userName) { + if (userName != null) { + log.info("Ending a session of user " + userName + + ", whose password changed or whose account was disabled or removed"); + } else { + log.debug("Logging out a request whose session another request ended"); + } // The session's other requests share this security context, so clear // the login from it before the session ends; otherwise one of them // could carry the login into a new session. From fd6bf9e707a3a457b043814c6a6d11a9f7208218 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Fri, 20 Nov 2026 14:06:18 -0700 Subject: [PATCH 23/25] Restore the password encoder in PasswordChangeSessionTest even when cleanup fails --- .../ui/core/PasswordChangeSessionTest.java | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java index f51aa33b86..9929f05bea 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java @@ -77,12 +77,14 @@ class PasswordChangeSessionTest { private String userName; private String adminName; private PasswordEncoder savedEncoder; + private boolean encoderSwapped; @BeforeEach void setUp() throws Exception { TestUtils.setupWeblogger(); savedEncoder = swapEncoder(new DelegatingPasswordEncoder("bcrypt", Map.of("bcrypt", new BCryptPasswordEncoder(4)))); + encoderSwapped = true; userName = TestUtils.setupUser("sessionuser").getUserName(); adminName = TestUtils.setupUser("sessionadmin").getUserName(); TestUtils.endSession(true); @@ -91,10 +93,20 @@ void setUp() throws Exception { @AfterEach void tearDown() throws Exception { SecurityContextHolder.clearContext(); - TestUtils.teardownUser(userName); - TestUtils.teardownUser(adminName); - TestUtils.endSession(true); - swapEncoder(savedEncoder); + try { + if (userName != null) { + TestUtils.teardownUser(userName); + } + if (adminName != null) { + TestUtils.teardownUser(adminName); + } + TestUtils.endSession(true); + } finally { + // later test classes must not run with this class's encoder + if (encoderSwapped) { + swapEncoder(savedEncoder); + } + } } @Test From 5495dc9c7470d418178c96be8002b9c9700303a0 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Fri, 20 Nov 2026 23:53:09 -0700 Subject: [PATCH 24/25] Send an ended session to the site root when its path would name another host A GET whose session was ended is sent back to the path it asked for. If that path starts with // or /\, which browsers read as another host, it now goes to the site root instead. --- .../ui/core/filters/LoadSaltFilter.java | 11 ++++++++ .../ui/core/filters/LoadSaltFilterTest.java | 27 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilter.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilter.java index 76ca3fbee6..234ab38611 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilter.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilter.java @@ -82,6 +82,9 @@ static boolean redirectEndedSession(HttpServletRequest request, HttpServletRespo target = request.getContextPath() + request.getServletPath() + (request.getPathInfo() != null ? request.getPathInfo() : "") + (request.getQueryString() != null ? "?" + request.getQueryString() : ""); + if (!isLocalPath(target)) { + target = request.getContextPath() + "/"; + } } else { target = request.getContextPath() + "/roller-ui/login.rol"; } @@ -89,6 +92,14 @@ static boolean redirectEndedSession(HttpServletRequest request, HttpServletRespo return true; } + /** + * True for a path on this site. A path that starts with // or /\ is read + * by browsers as another host, so it isn't one. + */ + static boolean isLocalPath(String path) { + return path.startsWith("/") && !path.startsWith("//") && !path.startsWith("/\\"); + } + /** Stylesheets, scripts and images get no session and no salt. */ static boolean isStaticFile(HttpServletRequest request) { String path = request.getServletPath(); diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilterTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilterTest.java index 28c175572a..ae1334bd8b 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilterTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilterTest.java @@ -93,6 +93,33 @@ void requestWhoseSessionWasEndedGoesBackToThePageItAskedFor() throws Exception { } } + @Test + void endedSessionIsNotRedirectedToAnotherHost() throws Exception { + try (MockedStatic mockedRollerSession = mockStatic(RollerSession.class)) { + mockedRollerSession.when(() -> RollerSession.getRollerSession(request)).thenReturn(rollerSession); + mockedRollerSession.when(() -> RollerSession.isSessionEnded(request)).thenReturn(true); + when(request.getDispatcherType()).thenReturn(DispatcherType.REQUEST); + when(request.getMethod()).thenReturn("GET"); + // Roller deployed at the root, and a path that a browser reads as a host + when(request.getContextPath()).thenReturn(""); + when(request.getServletPath()).thenReturn(""); + when(request.getPathInfo()).thenReturn("//example.com/page"); + + filter.doFilter(request, response, chain); + + verify(response).sendRedirect("/"); + verify(chain, never()).doFilter(request, response); + } + } + + @Test + void localPathsAreRecognized() { + org.junit.jupiter.api.Assertions.assertTrue(LoadSaltFilter.isLocalPath("/roller/roller-ui/menu.rol")); + org.junit.jupiter.api.Assertions.assertFalse(LoadSaltFilter.isLocalPath("//example.com/")); + org.junit.jupiter.api.Assertions.assertFalse(LoadSaltFilter.isLocalPath("/\\example.com/")); + org.junit.jupiter.api.Assertions.assertFalse(LoadSaltFilter.isLocalPath("https://example.com/")); + } + @Test void formPostWhoseSessionWasEndedGoesToTheLoginPage() throws Exception { try (MockedStatic mockedRollerSession = mockStatic(RollerSession.class)) { From 15c785c0e810932d6e7d1612ed87727e705352f2 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Sat, 21 Nov 2026 09:33:48 -0700 Subject: [PATCH 25/25] Build an ended session's redirect from the /roller-ui/ path The salt filter only sees /roller-ui/ requests, so a GET whose session was ended is sent back to /roller-ui/ plus the rest of its path, which can't name another host. Any other request goes to the login page, as a form post already does. This replaces the // and /\ check. --- .../ui/core/filters/LoadSaltFilter.java | 22 +++++++------------ .../ui/core/filters/LoadSaltFilterTest.java | 12 ++-------- 2 files changed, 10 insertions(+), 24 deletions(-) diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilter.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilter.java index 234ab38611..5fbf0675ac 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilter.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilter.java @@ -33,6 +33,8 @@ */ public class LoadSaltFilter implements Filter { + private static final String ROLLER_UI_PATH = "/roller-ui/"; + /** Roller UI static files, which never hold a form. */ static final String[] STATIC_PATHS = {"/roller-ui/styles/", "/roller-ui/scripts/", "/roller-ui/images/", "/roller-ui/theme/"}; @@ -77,14 +79,14 @@ static boolean redirectEndedSession(HttpServletRequest request, HttpServletRespo || request.getDispatcherType() != DispatcherType.REQUEST) { return false; } + String path = request.getServletPath() + + (request.getPathInfo() != null ? request.getPathInfo() : ""); String target; - if ("GET".equalsIgnoreCase(request.getMethod()) || "HEAD".equalsIgnoreCase(request.getMethod())) { - target = request.getContextPath() + request.getServletPath() - + (request.getPathInfo() != null ? request.getPathInfo() : "") + if (("GET".equalsIgnoreCase(request.getMethod()) || "HEAD".equalsIgnoreCase(request.getMethod())) + && path.startsWith(ROLLER_UI_PATH)) { + // Starting the redirect with /roller-ui/ keeps it on this site. + target = request.getContextPath() + ROLLER_UI_PATH + path.substring(ROLLER_UI_PATH.length()) + (request.getQueryString() != null ? "?" + request.getQueryString() : ""); - if (!isLocalPath(target)) { - target = request.getContextPath() + "/"; - } } else { target = request.getContextPath() + "/roller-ui/login.rol"; } @@ -92,14 +94,6 @@ static boolean redirectEndedSession(HttpServletRequest request, HttpServletRespo return true; } - /** - * True for a path on this site. A path that starts with // or /\ is read - * by browsers as another host, so it isn't one. - */ - static boolean isLocalPath(String path) { - return path.startsWith("/") && !path.startsWith("//") && !path.startsWith("/\\"); - } - /** Stylesheets, scripts and images get no session and no salt. */ static boolean isStaticFile(HttpServletRequest request) { String path = request.getServletPath(); diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilterTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilterTest.java index ae1334bd8b..3fcc9fa9c5 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilterTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilterTest.java @@ -94,7 +94,7 @@ void requestWhoseSessionWasEndedGoesBackToThePageItAskedFor() throws Exception { } @Test - void endedSessionIsNotRedirectedToAnotherHost() throws Exception { + void endedSessionOutsideTheAdminUiGoesToTheLoginPage() throws Exception { try (MockedStatic mockedRollerSession = mockStatic(RollerSession.class)) { mockedRollerSession.when(() -> RollerSession.getRollerSession(request)).thenReturn(rollerSession); mockedRollerSession.when(() -> RollerSession.isSessionEnded(request)).thenReturn(true); @@ -107,19 +107,11 @@ void endedSessionIsNotRedirectedToAnotherHost() throws Exception { filter.doFilter(request, response, chain); - verify(response).sendRedirect("/"); + verify(response).sendRedirect("/roller-ui/login.rol"); verify(chain, never()).doFilter(request, response); } } - @Test - void localPathsAreRecognized() { - org.junit.jupiter.api.Assertions.assertTrue(LoadSaltFilter.isLocalPath("/roller/roller-ui/menu.rol")); - org.junit.jupiter.api.Assertions.assertFalse(LoadSaltFilter.isLocalPath("//example.com/")); - org.junit.jupiter.api.Assertions.assertFalse(LoadSaltFilter.isLocalPath("/\\example.com/")); - org.junit.jupiter.api.Assertions.assertFalse(LoadSaltFilter.isLocalPath("https://example.com/")); - } - @Test void formPostWhoseSessionWasEndedGoesToTheLoginPage() throws Exception { try (MockedStatic mockedRollerSession = mockStatic(RollerSession.class)) {