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 a89bc3998a..f33f03bdb4 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,14 @@ 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.Collections; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; @@ -36,6 +43,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,11 +58,41 @@ 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; + + // digest of a password hash this session's own request is saving + private volatile String savingPasswordDigest = null; private static final Log log; 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"; + + // the longest chain of re-encodings a session is carried across, and how + // many re-encodings are remembered + private static final int MAX_REENCODINGS = 8; + private static final int MAX_REENCODED = 1000; + + // digests of password hashes that a login stored as a new encoding of an + // unchanged password, by user, each with the digest of the hash it + // replaced. A session that saw the older hash stays logged in. Entries + // that are dropped end those sessions instead. + private static final Map REENCODED = Collections.synchronizedMap( + new LinkedHashMap<>(16, 0.75f, true) { + @Override + protected boolean removeEldestEntry(Map.Entry eldest) { + return size() > MAX_REENCODED; + } + }); + + // 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); @@ -64,8 +102,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, null); + } + } + + private static RollerSession getRollerSession(HttpServletRequest request, HttpSession session) { + RollerSession rollerSession = null; if (session != null) { rollerSession = (RollerSession)session.getAttribute(ROLLER_SESSION); @@ -73,10 +124,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(session)) { + return endSession(request, session, rollerSession.userName); + } // 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); @@ -92,16 +151,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 @@ -119,7 +169,17 @@ 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, 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, principal.getName()); } } catch (WebloggerException e) { @@ -131,6 +191,236 @@ 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'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 rollerSession + && user.getUserName().equals(rollerSession.userName)) { + rollerSession.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 + * 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; + } + try { + Object attribute = session.getAttribute(ROLLER_SESSION); + if (attribute instanceof RollerSession rollerSession + && user.getUserName().equals(rollerSession.userName)) { + rollerSession.setAuthenticatedUser(user); + rollerSession.savingPasswordDigest = null; + rememberLoginPassword(session, rollerSession); + } + } catch (IllegalStateException e) { + if (!isInvalidated(session)) { + throw e; + } + // another request ended the session, there is no login to keep + } + } + + /** + * 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 samePassword(user, login.substring(prefix.length())); + } + + /** + * Records that a login stored a new encoding of the user's unchanged + * password, so that the user's sessions which saw the old one stay + * logged in. Call it before the new encoding is saved. + */ + public static void passwordReencoded(String userName, String oldPassword, String newPassword) { + REENCODED.put(userName + "\n" + digest(newPassword), digest(oldPassword)); + } + + /** + * Whether the user's password is the one a session saw, given as + * passwordDigest, or a re-encoding of it. + */ + private static boolean samePassword(User user, String passwordDigest) { + String current = digest(user); + for (int i = 0; current != null && i <= MAX_REENCODINGS; i++) { + if (current.equals(passwordDigest)) { + return true; + } + current = REENCODED.get(user.getUserName() + "\n" + current); + } + return false; + } + + private static void rememberLoginPassword(HttpSession session, RollerSession rollerSession) { + session.setAttribute(LOGIN_PASSWORD, rollerSession.userName + "\n" + rollerSession.passwordDigest); + } + + /** + * 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. A session that + * saw the password before it was re-encoded, or is saving a new password + * for its user, takes on the new one once it is stored. + */ + private boolean isCurrent(HttpSession session) { + 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; + } + if (user == null) { + return false; + } + if (digest(user).equals(savingPasswordDigest)) { + // the password this session's own request saved + savingPasswordDigest = null; + } else if (!samePassword(user, passwordDigest)) { + return false; + } + if (!digest(user).equals(passwordDigest)) { + passwordDigest = digest(user); + rememberLoginPassword(session, this); + } + return true; + } + + 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 + * 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, 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. + SecurityContextHolder.getContext().setAuthentication(null); + try { + session.invalidate(); + } catch (IllegalStateException ignored) { + // already invalidated + } + SecurityContextHolder.clearContext(); + request.setAttribute(SESSION_ENDED, Boolean.TRUE); + 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; + } + + /** + * 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) { + return digest(user.getPassword()); + } + + private static String digest(String storedPassword) { + String password = storedPassword != null ? storedPassword : ""; + 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 +468,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/core/filters/LoadSaltFilter.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilter.java index caa3a853bb..d06e1e764a 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 @@ -23,6 +23,7 @@ import java.security.SecureRandom; import jakarta.servlet.*; import jakarta.servlet.http.HttpServletRequest; +import jakarta.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; @@ -35,6 +36,8 @@ public class LoadSaltFilter implements Filter { static final String RENDERING_PATH = "/roller-ui/rendering/"; + 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/"}; @@ -50,6 +53,9 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha } 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(); @@ -89,6 +95,36 @@ static boolean isStaticFile(HttpServletRequest request) { return false; } + /** + * 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. + * Only the request the browser sent is redirected, not a forward. + * + * @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 path = request.getServletPath() + + (request.getPathInfo() != null ? request.getPathInfo() : ""); + String target; + 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() : ""); + } 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 748dc88bcc..1daf5101d1 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 @@ -63,6 +63,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/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..e090f97916 --- /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/RollerPasswordEncoders.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerPasswordEncoders.java index 3e1886af3c..883f9872ec 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; @@ -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 @@ -161,4 +174,21 @@ public boolean upgradeEncoding(String encodedPassword) { public static String randomUnusedPassword() { return RandomStringUtils.secure().nextAlphanumeric(64); } + + /** + * The longest password, in UTF-8 bytes, that BCrypt accepts. PBKDF2, + * SCrypt and Argon2 take longer ones, but the limit applies whatever the + * algorithm, so that a site can switch to BCrypt, the default, without + * leaving passwords it can't re-encode. + */ + 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/core/security/RollerRememberMeServices.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerRememberMeServices.java index ea8d4d28b2..07b47510d8 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/core/security/RollerUserDetailsService.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerUserDetailsService.java index 1d45492290..46729212fb 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerUserDetailsService.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerUserDetailsService.java @@ -36,6 +36,7 @@ import org.apache.roller.weblogger.business.WebloggerFactory; import org.apache.roller.weblogger.business.UserManager; import org.apache.roller.weblogger.pojos.User; +import org.apache.roller.weblogger.ui.core.RollerSession; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.dao.DataRetrievalFailureException; @@ -113,6 +114,8 @@ public UserDetails updatePassword(UserDetails user, String newPassword) { + ", which changed while they logged in"); return user; } + // the password did not change, so the user's sessions stay + RollerSession.passwordReencoded(userData.getUserName(), userData.getPassword(), newPassword); userData.setPassword(newPassword); umgr.saveUser(userData); roller.flush(); 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 7e66fb9959..63cd44bc9d 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; @@ -143,6 +144,7 @@ public String save() { myValidate(); if (!hasActionErrors()) { + String previousOpenIdUrl = user.getOpenIdUrl(); getBean().copyTo(user); if (authMethod == AuthMethod.DB_OIDC) { @@ -158,9 +160,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 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(StringUtils.removeEnd(previousOpenIdUrl, "/"), + StringUtils.removeEnd(user.getOpenIdUrl(), "/")))) { String randomString = RollerPasswordEncoders.randomUnusedPassword(); user.resetPassword(randomString); } @@ -191,6 +198,9 @@ public String save() { // save new user mgr.addUser(user); } else { + if (isUserEditingSelf()) { + RollerSession.savingPassword(getServletRequest(), user); + } mgr.saveUser(user); } @@ -214,6 +224,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"); @@ -231,7 +247,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/ajax/CommentDataServlet.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/ajax/CommentDataServlet.java index f329cf6f3b..d6a60967e8 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 @@ -65,7 +65,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()) @@ -106,7 +106,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 @@ -138,6 +138,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/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 49bccca2ae..a1ca6fdff2 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; @@ -75,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); @@ -106,9 +108,15 @@ 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(StringUtils.removeEnd(previousOpenIdUrl, "/"), + StringUtils.removeEnd(existingUser.getOpenIdUrl(), "/")))) { String randomString = RollerPasswordEncoders.randomUnusedPassword(); existingUser.resetPassword(randomString); } @@ -121,9 +129,12 @@ 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(); + RollerSession.refreshPassword(getServletRequest(), existingUser); addMessage("generic.changes.saved"); return SUCCESS; } catch (WebloggerException ex) { @@ -135,6 +146,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"); 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 7f89da85fc..78ad48c98e 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"; } @@ -212,7 +216,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()); } @@ -414,29 +420,35 @@ 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; } // 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 { + // (with LDAP or CMA the bean holds the marker, not a typed password) + if (!usingSSO && RollerPasswordEncoders.isTooLong(getBean().getPasswordText())) { + addError("userRegister.error.passwordTooLong"); + } + + // 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 (!StringUtils.equals(getBean().getPasswordText(), 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 deb045f0c0..574e03c6ff 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. 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/main/webapp/WEB-INF/security.xml b/app/src/main/webapp/WEB-INF/security.xml index 7529ad6643..7e2beaa752 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"> + + + + +