From 32d476caae0712ad12cbe99c3f5e2901e8c9cae5 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Tue, 17 Nov 2026 16:34:31 -0700 Subject: [PATCH 01/20] 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. 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. --- .../weblogger/ui/core/RollerSession.java | 90 +++++- .../weblogger/ui/struts2/admin/UserEdit.java | 7 + .../weblogger/ui/struts2/core/Profile.java | 3 + .../ui/core/PasswordChangeSessionTest.java | 303 ++++++++++++++++++ 4 files changed, 401 insertions(+), 2 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 a89bc3998..764c15c37 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 @@ -20,7 +20,11 @@ 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 java.util.HexFormat; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; @@ -36,6 +40,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.RollerOidcUserService; +import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; import org.springframework.security.oauth2.core.oidc.user.OidcUser; @@ -50,6 +55,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; @@ -73,10 +81,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); @@ -131,6 +147,75 @@ 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 rollerSession + && user.getUserName().equals(rollerSession.userName)) { + rollerSession.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"); + return HexFormat.of().formatHex(sha.digest(password.getBytes(StandardCharsets.UTF_8))); + } 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) { @@ -178,6 +263,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 cb77e1750..477842112 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 @@ -39,6 +39,7 @@ 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.parameter.StrutsParameter; @@ -214,6 +215,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"); 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 9671fb0d3..cdb741c18 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.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.parameter.StrutsParameter; import org.apache.struts2.interceptor.validation.SkipValidation; @@ -124,6 +125,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) { 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 000000000..e91366533 --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/PasswordChangeSessionTest.java @@ -0,0 +1,303 @@ +/* + * 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 jakarta.servlet.http.HttpServletRequest; +import jakarta.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.core.security.RollerPasswordEncoders; +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.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(RollerPasswordEncoders.create()); + 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.withServletRequest(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 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.withServletRequest(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 8fd7bae1d0c8042f32b4651bf8bb4151738fcf78 Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Tue, 17 Nov 2026 19:47:54 -0700 Subject: [PATCH 02/20] Keep the stored password when an OIDC account's profile is saved without a sign-in change Profile.save and UserEdit.save generated a new random stored password for OIDC 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 OIDC account with another session open, and switching an account to OpenID. --- .../weblogger/ui/struts2/admin/UserEdit.java | 11 +- .../weblogger/ui/struts2/core/Profile.java | 12 +- .../ui/core/PasswordChangeSessionTest.java | 120 +++++++++++++++++- 3 files changed, 134 insertions(+), 9 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 477842112..98addaa31 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 @@ -144,6 +144,7 @@ public String save() { myValidate(); if (!hasActionErrors()) { + String previousOpenIdUrl = user.getOpenIdUrl(); getBean().copyTo(user); if (authMethod == AuthMethod.DB_OIDC) { @@ -159,9 +160,13 @@ public String save() { } } - // User.password does not allow null, so generate one - if (authMethod.equals(AuthMethod.OIDC) || - (authMethod.equals(AuthMethod.DB_OIDC) && !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.OIDC) || + (authMethod.equals(AuthMethod.DB_OIDC) && !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 cdb741c18..08c580093 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 @@ -76,6 +76,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); @@ -107,9 +108,14 @@ public String save() { } } - // User.password does not allow null, so generate one - if (authMethod.equals(AuthMethod.OIDC) || - (authMethod.equals(AuthMethod.DB_OIDC) && !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 a profile edit doesn't end the user's + // other sessions. + if ((authMethod.equals(AuthMethod.OIDC) || + (authMethod.equals(AuthMethod.DB_OIDC) && !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 e91366533..2c931916d 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.core.security.RollerPasswordEncoders; import org.apache.roller.weblogger.ui.struts2.admin.CreateUserBean; @@ -41,10 +42,13 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.crypto.password.DelegatingPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder; 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; @@ -105,7 +109,7 @@ void changingOwnPasswordEndsTheUsersOtherSessions() throws Exception { profile.setBean(bean); profile.setAuthenticatedUser(self); profile.withServletRequest(a.httpRequest); - assertEquals(Profile.SUCCESS, profile.save()); + assertEquals(Profile.SUCCESS, profile.save(), () -> String.valueOf(profile.getActionErrors())); TestUtils.endSession(true); b.assertLoggedOut(); @@ -151,7 +155,7 @@ void adminChangingOwnPasswordStaysLoggedIn() throws Exception { admin.request(); UserEdit action = userEdit(admin, adminName); action.getBean().setPassword("reset-password"); - assertEquals(UserEdit.SUCCESS, action.save()); + assertEquals(UserEdit.SUCCESS, action.save(), () -> String.valueOf(action.getActionErrors())); TestUtils.endSession(true); other.assertLoggedOut(); @@ -171,12 +175,122 @@ void savingWithoutAPasswordChangeKeepsOtherSessions() throws Exception { b.assertLoggedIn(userName); } + @Test + void oidcProfileEditKeepsTheUsersOtherSessions() throws Exception { + useHashedPasswords(); + linkOpenId(userName, "https://idp.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.OIDC); + User self = user(userName); + ProfileBean bean = new ProfileBean(); + bean.copyFrom(self); + bean.setScreenName("Renamed"); + profile.setBean(bean); + profile.setAuthenticatedUser(self); + profile.withServletRequest(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 adminEditOfAnOidcUserKeepsTheirSessions() throws Exception { + useHashedPasswords(); + linkOpenId(userName, "https://idp.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_OIDC); + 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 switchingToOidcReplacesTheStoredPassword() throws Exception { + useHashedPasswords(); + 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_OIDC); + action.getBean().setOpenIdUrl("https://idp.example.com/sessionuser"); + assertEquals(UserEdit.SUCCESS, action.save(), () -> String.valueOf(action.getActionErrors())); + TestUtils.endSession(true); + + assertNotEquals(storedPassword, user(userName).getPassword()); + b.assertLoggedOut(); + } + + /** + * The test configuration stores passwords in plain text, and a generated + * 255-character password doesn't fit the column that way. tearDown puts + * the configured encoder back. + */ + private static void useHashedPasswords() throws Exception { + swapEncoder(new DelegatingPasswordEncoder("pbkdf2", + Map.of("pbkdf2", Pbkdf2PasswordEncoder.defaultsForSpringSecurity_v5_8()))); + } + + 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(); UserEdit action = userEdit(admin, userName); change.accept(action.getBean()); - assertEquals(UserEdit.SUCCESS, action.save()); + assertEquals(UserEdit.SUCCESS, action.save(), () -> String.valueOf(action.getActionErrors())); TestUtils.endSession(true); } From babfe8ff678e0ab79c7db16e513938609f01432e Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Tue, 17 Nov 2026 19:54:36 -0700 Subject: [PATCH 03/20] 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 764c15c37..abf58e36f 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,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); @@ -135,7 +139,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) { @@ -161,7 +171,25 @@ public static void refreshPassword(HttpServletRequest request, User user) { if (attribute instanceof RollerSession rollerSession && user.getUserName().equals(rollerSession.userName)) { rollerSession.setAuthenticatedUser(user); + rememberLoginPassword(session, rollerSession); + } + } + + /** + * 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 login) || !login.startsWith(prefix)) { + return true; } + return login.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 2c931916d..beeaa7dd6 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 jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; +import jakarta.servlet.http.HttpSessionEvent; import org.apache.roller.weblogger.TestUtils; import org.apache.roller.weblogger.business.UserManager; import org.apache.roller.weblogger.business.WebloggerFactory; @@ -285,6 +286,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.withServletRequest(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(); @@ -366,6 +410,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; @@ -385,6 +434,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 49f9108bd97bfaff2d7cb303995cf5aa82f2393f Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Tue, 17 Nov 2026 19:56:22 -0700 Subject: [PATCH 04/20] Say when a typed password is too long, and keep the generated one out of the form A password over 72 bytes in UTF-8, for example 20 emoji, made BCrypt throw when Register, Profile or UserEdit saved it, so the user got an error page. The forms now check the length first and say the password is too long. Register also put the random password it generates for OIDC users in the form's hidden password fields, so a registration that failed validation, for example on a taken user name, sent it back to the browser. It now keeps that password in the action and only uses it when saving the user. --- .../core/security/RollerPasswordEncoders.java | 17 ++- .../weblogger/ui/struts2/admin/UserEdit.java | 5 +- .../weblogger/ui/struts2/core/Profile.java | 3 + .../weblogger/ui/struts2/core/Register.java | 38 ++++-- .../resources/ApplicationResources.properties | 1 + .../admin/UserEditPasswordLengthTest.java | 43 ++++++ .../core/PasswordFormValidationTest.java | 125 ++++++++++++++++++ 7 files changed, 216 insertions(+), 16 deletions(-) create mode 100644 app/src/test/java/org/apache/roller/weblogger/ui/struts2/admin/UserEditPasswordLengthTest.java create mode 100644 app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/PasswordFormValidationTest.java diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerPasswordEncoders.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerPasswordEncoders.java index 263102981..9a8208587 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerPasswordEncoders.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerPasswordEncoders.java @@ -17,7 +17,7 @@ package org.apache.roller.weblogger.ui.core.security; - +import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; @@ -158,4 +158,19 @@ public boolean upgradeEncoding(String encodedPassword) { public static String randomUnusedPassword() { return RandomStringUtils.secure().nextAlphanumeric(64); } + + /** + * The longest password, in UTF-8 bytes, that every encoder accepts. BCrypt + * refuses longer ones. + */ + public static final int MAX_PASSWORD_BYTES = 72; + + /** + * Returns true when a typed password is longer than an encoder accepts, so + * that a form can say so instead of failing when the password is encoded. + */ + public static boolean isTooLong(String password) { + return password != null + && password.getBytes(StandardCharsets.UTF_8).length > MAX_PASSWORD_BYTES; + } } 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 a0aaaf353..63b1c7637 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 @@ -232,7 +232,10 @@ private boolean isAdd() { return actionName.equals("createUser"); } - private void myValidate() { + void myValidate() { + if (RollerPasswordEncoders.isTooLong(getBean().getPassword())) { + addError("userRegister.error.passwordTooLong"); + } // the external-login marker never matches at login if (RollerPasswordEncoders.isExternalLoginMarker(getBean().getPassword())) { addError("error.add.user.reservedPassword"); 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 9be587542..aaaf66f9d 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 @@ -145,6 +145,9 @@ public void myValidate() { if (!StringUtils.equals(getBean().getPasswordText(), getBean().getPasswordConfirm())) { addError("userRegister.error.mismatchedPasswords"); } + if (RollerPasswordEncoders.isTooLong(getBean().getPasswordText())) { + addError("userRegister.error.passwordTooLong"); + } if (authMethod == AuthMethod.OIDC) { addError("userRegister.error.missingOpenID"); } 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 48f0a3ce7..16a2e7249 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 @@ -70,6 +70,10 @@ public class Register extends UIAction { private String activationCode = null; private ProfileBean bean = new ProfileBean(); + // generated for OIDC users, kept out of the bean so that the form never + // renders it + private String unusedPassword = null; + public Register() { this.pageTitle = "newUser.addNewUser"; } @@ -211,7 +215,9 @@ public String save() { ud.setEnabled(Boolean.TRUE); // If user set both password and passwordConfirm then reset password - if (!StringUtils.isEmpty(getBean().getPasswordText()) && + if (unusedPassword != null) { + ud.resetPassword(unusedPassword); + } else if (!StringUtils.isEmpty(getBean().getPasswordText()) && !StringUtils.isEmpty(getBean().getPasswordConfirm())) { ud.resetPassword(getBean().getPasswordText()); } @@ -383,22 +389,26 @@ public void myValidate() { } // User.password does not allow null, so generate one for OIDC users + unusedPassword = null; if (getAuthMethod().equals(AuthMethod.OIDC.name()) || (getAuthMethod().equals(AuthMethod.DB_OIDC.name()) && !StringUtils.isEmpty(getBean().getOpenIdUrl()))) { - String randomString = RollerPasswordEncoders.randomUnusedPassword(); - getBean().setPasswordText(randomString); - getBean().setPasswordConfirm(randomString); - } - - // the external-login marker is stored for users who log in elsewhere - // and never matches at login - if (!usingSSO && RollerPasswordEncoders.isExternalLoginMarker(getBean().getPasswordText())) { - addError("error.add.user.reservedPassword"); - } + unusedPassword = RollerPasswordEncoders.randomUnusedPassword(); + } else { + if (RollerPasswordEncoders.isTooLong(getBean().getPasswordText())) { + addError("userRegister.error.passwordTooLong"); + return; + } + + // the external-login marker is stored for users who log in + // elsewhere and never matches at login + if (!usingSSO && RollerPasswordEncoders.isExternalLoginMarker(getBean().getPasswordText())) { + addError("error.add.user.reservedPassword"); + } - // check that passwords match - if (!getBean().getPasswordText().equals(getBean().getPasswordConfirm())) { - addError("userRegister.error.mismatchedPasswords"); + // check that passwords match + if (!StringUtils.equals(getBean().getPasswordText(), getBean().getPasswordConfirm())) { + addError("userRegister.error.mismatchedPasswords"); + } } // check that username is not taken diff --git a/app/src/main/resources/ApplicationResources.properties b/app/src/main/resources/ApplicationResources.properties index 387e4a0ad..a6f61b45f 100644 --- a/app/src/main/resources/ApplicationResources.properties +++ b/app/src/main/resources/ApplicationResources.properties @@ -1522,6 +1522,7 @@ userRegister.button.save=Sign Up userRegister.success.ready=Yes, form appears to be complete. Click the button below. userRegister.error.mismatchedPasswords=Your passwords do not match! +userRegister.error.passwordTooLong=Your password is too long. Use at most 72 characters, or fewer if it has accented letters, symbols or emoji. userRegister.error.missingOpenID=Open ID URL must be provided. userRegister.error.missingOpenIDOrPassword=Either an Open ID URL or a password must be provided. userRegister.error.bothOpenIDAndPassword=Please supply just a password or an OpenID (not both). diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/admin/UserEditPasswordLengthTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/admin/UserEditPasswordLengthTest.java new file mode 100644 index 000000000..56e1c8a7b --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/admin/UserEditPasswordLengthTest.java @@ -0,0 +1,43 @@ +/* + * 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.admin; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class UserEditPasswordLengthTest { + + @Test + void rejectsPasswordTooLongToEncode() { + UserEdit action = new UserEdit() { + @Override + public String getText(String key) { + return key; + } + }; + action.setActionName("createUser"); + action.getBean().setUserName("emoji"); + // 20 emoji, 80 bytes in UTF-8 + action.getBean().setPassword("😀".repeat(20)); + action.myValidate(); + assertTrue(action.getActionErrors().contains("userRegister.error.passwordTooLong")); + assertEquals(1, action.getActionErrors().size(), action.getActionErrors().toString()); + } +} diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/PasswordFormValidationTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/PasswordFormValidationTest.java new file mode 100644 index 000000000..2d822af41 --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/PasswordFormValidationTest.java @@ -0,0 +1,125 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.roller.weblogger.ui.struts2.core; + +import java.lang.reflect.Field; + +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.AuthMethod; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + +/** + * Passwords that the encoder can't take get a form error, and a password + * generated for an OIDC user is never put in the form. + */ +class PasswordFormValidationTest { + + // 20 emoji, 80 bytes in UTF-8 + private static final String TOO_LONG = "😀".repeat(20); + // 72 bytes in UTF-8 + private static final String LONGEST = "a".repeat(72); + + @Test + void profileRejectsPasswordTooLongToEncode() { + Profile action = new Profile() { + @Override + public String getText(String key) { + return key; + } + }; + action.getBean().setPasswordText(TOO_LONG); + action.getBean().setPasswordConfirm(TOO_LONG); + action.myValidate(); + assertTrue(action.getActionErrors().contains("userRegister.error.passwordTooLong")); + } + + @Test + void profileAcceptsLongestPassword() { + Profile action = new Profile() { + @Override + public String getText(String key) { + return key; + } + }; + action.getBean().setPasswordText(LONGEST); + action.getBean().setPasswordConfirm(LONGEST); + action.myValidate(); + assertFalse(action.getActionErrors().contains("userRegister.error.passwordTooLong")); + } + + @Test + void registerRejectsPasswordTooLongToEncode() throws Exception { + Register action = register(AuthMethod.ROLLERDB); + action.getBean().setUserName("emoji"); + action.getBean().setPasswordText(TOO_LONG); + action.getBean().setPasswordConfirm(TOO_LONG); + try (MockedStatic factory = mockUserManager()) { + action.myValidate(); + } + assertTrue(action.getActionErrors().contains("userRegister.error.passwordTooLong")); + } + + @Test + void registerKeepsGeneratedPasswordOutOfTheForm() throws Exception { + Register action = register(AuthMethod.DB_OIDC); + action.getBean().setUserName("taken"); + action.getBean().setOpenIdUrl("https://idp.example.com#taken"); + try (MockedStatic factory = mockUserManager()) { + action.myValidate(); + } + // the form is shown again with an error, and must not carry the password + assertTrue(action.getActionErrors().contains("error.add.user.userNameInUse")); + assertNull(action.getBean().getPasswordText()); + assertNull(action.getBean().getPasswordConfirm()); + assertNull(action.getBean().getPassword()); + } + + private static Register register(AuthMethod authMethod) throws Exception { + Register action = new Register() { + @Override + public String getText(String key) { + return key; + } + }; + Field field = Register.class.getDeclaredField("authMethod"); + field.setAccessible(true); + field.set(action, authMethod); + return action; + } + + private static MockedStatic mockUserManager() throws Exception { + UserManager userManager = mock(UserManager.class); + when(userManager.getUserByUserName("taken", null)) + .thenReturn(new org.apache.roller.weblogger.pojos.User()); + Weblogger weblogger = mock(Weblogger.class); + when(weblogger.getUserManager()).thenReturn(userManager); + MockedStatic factory = mockStatic(WebloggerFactory.class); + factory.when(WebloggerFactory::getWeblogger).thenReturn(weblogger); + return factory; + } +} From 99d7be7da731df1f6be8a6781b55571c220e2e5e Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Tue, 17 Nov 2026 20:20:09 -0700 Subject: [PATCH 05/20] Check the password length on profiles that also have an OpenID URL Profile only checked a typed password's length when no OpenID URL was given, but it saves a typed password either way, so a long one with an OpenID URL still failed in BCrypt. --- .../weblogger/ui/struts2/core/Profile.java | 6 +++--- .../core/PasswordFormValidationTest.java | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) 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 aaaf66f9d..3afc607fd 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 @@ -136,6 +136,9 @@ public String save() { } public void myValidate() { + if (RollerPasswordEncoders.isTooLong(getBean().getPasswordText())) { + addError("userRegister.error.passwordTooLong"); + } // the external-login marker never matches at login if (RollerPasswordEncoders.isExternalLoginMarker(getBean().getPasswordText())) { addError("error.add.user.reservedPassword"); @@ -145,9 +148,6 @@ public void myValidate() { if (!StringUtils.equals(getBean().getPasswordText(), getBean().getPasswordConfirm())) { addError("userRegister.error.mismatchedPasswords"); } - if (RollerPasswordEncoders.isTooLong(getBean().getPasswordText())) { - addError("userRegister.error.passwordTooLong"); - } if (authMethod == AuthMethod.OIDC) { addError("userRegister.error.missingOpenID"); } diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/PasswordFormValidationTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/PasswordFormValidationTest.java index 2d822af41..a3535a2ab 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/PasswordFormValidationTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/PasswordFormValidationTest.java @@ -58,6 +58,25 @@ public String getText(String key) { assertTrue(action.getActionErrors().contains("userRegister.error.passwordTooLong")); } + @Test + void profileRejectsPasswordTooLongToEncodeWithOpenIdUrl() { + Profile action = new Profile() { + @Override + public String getText(String key) { + return key; + } + }; + action.getBean().setOpenIdUrl("https://idp.example.com#emoji"); + action.getBean().setPasswordText(TOO_LONG); + action.getBean().setPasswordConfirm(TOO_LONG); + try (MockedStatic factory = mockUserManager()) { + action.myValidate(); + } catch (Exception e) { + throw new AssertionError(e); + } + assertTrue(action.getActionErrors().contains("userRegister.error.passwordTooLong")); + } + @Test void profileAcceptsLongestPassword() { Profile action = new Profile() { From 082ad37012906b2a1e6a5da4862e2d62f1cdfacc Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Wed, 18 Nov 2026 21:20:48 -0700 Subject: [PATCH 06/20] Let long legacy passwords log in, and tighten registration password checks A user whose password is stored with an older encoding and is longer than BCrypt's 72 bytes can log in again. The encoder returns no re-encoding for such a password instead of throwing, so the login succeeds and the stored password is left as it is. Registration under db-oidc now asks for a password when neither a password nor an OpenID URL is given, instead of failing when the user is saved. The missing-password error uses error.add.user.missingPassword, which exists in the message bundle. The length check no longer runs for LDAP and container-managed sign-ups, where the form holds the configured placeholder rather than a typed password. The too-long message no longer promises 72 characters, since the limit is in bytes and the form fields are shorter than that. --- .../core/security/RollerPasswordEncoders.java | 15 +++- .../weblogger/ui/struts2/core/Register.java | 9 +- .../resources/ApplicationResources.properties | 2 +- .../ui/core/security/PasswordUpgradeTest.java | 19 +++++ .../core/ExternalLoginMarkerPasswordTest.java | 2 +- .../core/PasswordFormValidationTest.java | 84 ++++++++++++++++++- 6 files changed, 124 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerPasswordEncoders.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerPasswordEncoders.java index eeac520bb..9332cfaec 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerPasswordEncoders.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerPasswordEncoders.java @@ -130,9 +130,22 @@ public static PasswordEncoder create() { */ private record ExternalLoginAware(PasswordEncoder delegate) implements PasswordEncoder { + /** + * Returns null for a password that BCrypt refuses as too long. A + * login re-encodes the password it has just checked against an older + * encoding, and for such a password that login has to succeed and + * leave the stored password as it is. + */ @Override public String encode(CharSequence rawPassword) { - return delegate.encode(rawPassword); + try { + return delegate.encode(rawPassword); + } catch (IllegalArgumentException e) { + if (rawPassword != null && isTooLong(rawPassword.toString())) { + return null; + } + throw e; + } } @Override 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 4f428e41a..2c59269a4 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 @@ -381,9 +381,11 @@ public void myValidate() { } // check password, it is required if OpenID and SSO are disabled - if (AuthMethod.ROLLERDB.name().equals(getAuthMethod()) + if ((AuthMethod.ROLLERDB.name().equals(getAuthMethod()) + || (AuthMethod.DB_OIDC.name().equals(getAuthMethod()) + && StringUtils.isEmpty(getBean().getOpenIdUrl()))) && StringUtils.isEmpty(getBean().getPasswordText())) { - addError("error.add.user.passwordEmpty"); + addError("error.add.user.missingPassword"); return; } @@ -393,7 +395,8 @@ public void myValidate() { (getAuthMethod().equals(AuthMethod.DB_OIDC.name()) && !StringUtils.isEmpty(getBean().getOpenIdUrl()))) { unusedPassword = RollerPasswordEncoders.randomUnusedPassword(); } else { - if (RollerPasswordEncoders.isTooLong(getBean().getPasswordText())) { + // (with LDAP or CMA the bean holds the marker, not a typed password) + if (!usingSSO && RollerPasswordEncoders.isTooLong(getBean().getPasswordText())) { addError("userRegister.error.passwordTooLong"); return; } diff --git a/app/src/main/resources/ApplicationResources.properties b/app/src/main/resources/ApplicationResources.properties index a6f61b45f..a900c86e6 100644 --- a/app/src/main/resources/ApplicationResources.properties +++ b/app/src/main/resources/ApplicationResources.properties @@ -1522,7 +1522,7 @@ userRegister.button.save=Sign Up userRegister.success.ready=Yes, form appears to be complete. Click the button below. userRegister.error.mismatchedPasswords=Your passwords do not match! -userRegister.error.passwordTooLong=Your password is too long. Use at most 72 characters, or fewer if it has accented letters, symbols or emoji. +userRegister.error.passwordTooLong=Your password is too long. Accented letters, non-Latin characters and emoji take up more room than other characters, so use fewer of them or a shorter password. userRegister.error.missingOpenID=Open ID URL must be provided. userRegister.error.missingOpenIDOrPassword=Either an Open ID URL or a password must be provided. userRegister.error.bothOpenIDAndPassword=Please supply just a password or an OpenID (not both). diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/security/PasswordUpgradeTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/security/PasswordUpgradeTest.java index f38522b30..06a18cfca 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/core/security/PasswordUpgradeTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/security/PasswordUpgradeTest.java @@ -100,6 +100,25 @@ void successfulLoginStoresTheConfiguredEncoding() throws Exception { assertEquals(stored, storedPassword(), "an up-to-date hash is left alone"); } + @Test + void aPasswordTooLongToReEncodeStillLogsIn() throws Exception { + // 73 bytes, one more than BCrypt encodes + String longPassword = "a".repeat(73); + String longHash = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1") + .digest(longPassword.getBytes(StandardCharsets.UTF_8))); + UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); + User user = mgr.getUserByUserName(userName); + user.setPassword(longHash); + mgr.saveUser(user); + TestUtils.endSession(true); + + assertTrue(provider().authenticate(UsernamePasswordAuthenticationToken.unauthenticated( + userName, longPassword)).isAuthenticated()); + TestUtils.endSession(true); + + assertEquals(longHash, storedPassword()); + } + @Test void failedLoginLeavesThePasswordAlone() throws Exception { assertThrows(BadCredentialsException.class, () -> provider().authenticate( 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 a76f131f5..3e68e8aec 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 @@ -127,7 +127,7 @@ void registrationAcceptsAnOrdinaryPassword() { @Test void registrationWithoutAPasswordDoesNotFail() throws Exception { - // db-oidc does not require a password when the form is validated + // neither a password nor an OpenID URL is typed setProperty("authentication.method", "db-oidc"); Register action = withText(new Register()); action.getBean().setUserName("newuser"); diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/PasswordFormValidationTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/PasswordFormValidationTest.java index a3535a2ab..c0cbb9eda 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/PasswordFormValidationTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/PasswordFormValidationTest.java @@ -17,15 +17,22 @@ package org.apache.roller.weblogger.ui.struts2.core; +import java.io.InputStream; import java.lang.reflect.Field; +import java.util.List; +import java.util.Properties; + +import jakarta.servlet.http.HttpServletRequest; 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.AuthMethod; +import org.apache.roller.weblogger.config.WebloggerConfig; 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.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -43,6 +50,7 @@ class PasswordFormValidationTest { private static final String TOO_LONG = "😀".repeat(20); // 72 bytes in UTF-8 private static final String LONGEST = "a".repeat(72); + private static final String MARKER = "users.passwords.externalAuthValue"; @Test void profileRejectsPasswordTooLongToEncode() { @@ -103,6 +111,62 @@ void registerRejectsPasswordTooLongToEncode() throws Exception { assertTrue(action.getActionErrors().contains("userRegister.error.passwordTooLong")); } + @Test + void registerRequiresAPasswordInDatabaseMode() throws Exception { + Register action = register(AuthMethod.ROLLERDB); + action.getBean().setUserName("nopassword"); + try (MockedStatic factory = mockUserManager()) { + action.myValidate(); + } + assertEquals(List.of("error.add.user.missingPassword"), List.copyOf(action.getActionErrors())); + assertTrue(messages().containsKey("error.add.user.missingPassword")); + } + + @Test + void registerRequiresAPasswordWithoutAnOpenIdUrl() throws Exception { + Register action = register(AuthMethod.DB_OIDC); + action.getBean().setUserName("nopassword"); + try (MockedStatic factory = mockUserManager()) { + action.myValidate(); + } + assertEquals(List.of("error.add.user.missingPassword"), List.copyOf(action.getActionErrors())); + } + + @Test + void registerDoesNotMeasureThePlaceholderOfAnExternalLogin() throws Exception { + Properties config = config(); + String saved = config.getProperty(MARKER); + // longer than a typed password may be + config.setProperty(MARKER, "x".repeat(80)); + try (MockedStatic factory = mockUserManager()) { + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getUserPrincipal()).thenReturn(() -> "cmauser"); + Register action = new Register() { + @Override + public String getText(String key) { + return key; + } + + @Override + protected HttpServletRequest getServletRequest() { + return request; + } + }; + setAuthMethod(action, AuthMethod.CMA); + + action.myValidate(); + + assertEquals("cmauser", action.getBean().getUserName()); + assertFalse(action.hasActionErrors(), action.getActionErrors().toString()); + } finally { + if (saved == null) { + config.remove(MARKER); + } else { + config.setProperty(MARKER, saved); + } + } + } + @Test void registerKeepsGeneratedPasswordOutOfTheForm() throws Exception { Register action = register(AuthMethod.DB_OIDC); @@ -125,10 +189,28 @@ public String getText(String key) { return key; } }; + setAuthMethod(action, authMethod); + return action; + } + + private static void setAuthMethod(Register action, AuthMethod authMethod) throws Exception { Field field = Register.class.getDeclaredField("authMethod"); field.setAccessible(true); field.set(action, authMethod); - return action; + } + + private static Properties config() throws ReflectiveOperationException { + Field field = WebloggerConfig.class.getDeclaredField("config"); + field.setAccessible(true); + return (Properties) field.get(null); + } + + private static Properties messages() throws Exception { + Properties messages = new Properties(); + try (InputStream in = Register.class.getResourceAsStream("/ApplicationResources.properties")) { + messages.load(in); + } + return messages; } private static MockedStatic mockUserManager() throws Exception { From feb3c2e6fd7b3d3c6b513a13f42dc17d6f4d87af Mon Sep 17 00:00:00 2001 From: Matt Raible Date: Wed, 18 Nov 2026 21:22:14 -0700 Subject: [PATCH 07/20] 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 | 92 +++++-- .../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 | 20 +- .../ui/core/PasswordChangeSessionTest.java | 257 +++++++++++++++++- 7 files changed, 413 insertions(+), 27 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 abf58e36f..eb3d262ff 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 @@ -76,8 +76,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); @@ -112,16 +125,7 @@ public static RollerSession getRollerSession(HttpServletRequest request) { try { UserManager umgr = WebloggerFactory.getWeblogger().getUserManager(); - User user = umgr.getUserByUserName(principal.getName()); - - // For OIDC-authenticated users, look up by OIDC subject - if (user == null && principal instanceof OAuth2AuthenticationToken oauthToken) { - Object oauthPrincipal = oauthToken.getPrincipal(); - if (oauthPrincipal instanceof OidcUser oidcUser) { - String oidcSubject = RollerOidcUserService.toOidcSubject(oidcUser); - user = umgr.getUserByOpenIdUrl(oidcSubject); - } - } + 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 @@ -157,6 +161,46 @@ 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()); + + // For OIDC-authenticated users, look up by OIDC subject + if (user == null && principal instanceof OAuth2AuthenticationToken oauthToken) { + Object oauthPrincipal = oauthToken.getPrincipal(); + if (oauthPrincipal instanceof OidcUser oidcUser) { + String oidcSubject = RollerOidcUserService.toOidcSubject(oidcUser); + user = umgr.getUserByOpenIdUrl(oidcSubject); + } + } + 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 @@ -167,11 +211,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 rollerSession - && user.getUserName().equals(rollerSession.userName)) { - rollerSession.setAuthenticatedUser(user); - rememberLoginPassword(session, rollerSession); + try { + Object attribute = session.getAttribute(ROLLER_SESSION); + if (attribute instanceof RollerSession rollerSession + && user.getUserName().equals(rollerSession.userName)) { + rollerSession.setAuthenticatedUser(user); + rememberLoginPassword(session, rollerSession); + } + } catch (IllegalStateException e) { + if (!isInvalidated(session)) { + throw e; + } + // another request ended the session, there is no login to keep } } @@ -210,6 +261,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 000000000..e090f9791 --- /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 jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.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 9e5742bb8..bf1404969 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 @@ -23,10 +23,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 jakarta.servlet.http.HttpServletRequest; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -50,6 +54,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 652f7eb34..bb1369f1e 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 @@ -167,7 +167,8 @@ public String save() { if ((authMethod.equals(AuthMethod.OIDC) || (authMethod.equals(AuthMethod.DB_OIDC) && !StringUtils.isEmpty(bean.getOpenIdUrl()))) && (StringUtils.isEmpty(user.getPassword()) - || !StringUtils.equals(previousOpenIdUrl, user.getOpenIdUrl()))) { + || !StringUtils.equals(StringUtils.removeEnd(previousOpenIdUrl, "/"), + StringUtils.removeEnd(user.getOpenIdUrl(), "/")))) { String randomString = RollerPasswordEncoders.randomUnusedPassword(); 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 eb19c8c49..01c5f90dd 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 @@ -116,7 +116,8 @@ public String save() { if ((authMethod.equals(AuthMethod.OIDC) || (authMethod.equals(AuthMethod.DB_OIDC) && !StringUtils.isEmpty(bean.getOpenIdUrl()))) && (StringUtils.isEmpty(existingUser.getPassword()) - || !StringUtils.equals(previousOpenIdUrl, existingUser.getOpenIdUrl()))) { + || !StringUtils.equals(StringUtils.removeEnd(previousOpenIdUrl, "/"), + StringUtils.removeEnd(existingUser.getOpenIdUrl(), "/")))) { String randomString = RollerPasswordEncoders.randomUnusedPassword(); existingUser.resetPassword(randomString); } diff --git a/app/src/main/webapp/WEB-INF/security.xml b/app/src/main/webapp/WEB-INF/security.xml index 7529ad664..7e2beaa75 100644 --- a/app/src/main/webapp/WEB-INF/security.xml +++ b/app/src/main/webapp/WEB-INF/security.xml @@ -45,6 +45,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"> + + + + +