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 a1b1caf33..c7eb93604 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/RollerSession.java @@ -19,6 +19,9 @@ package org.apache.roller.weblogger.ui.core; import java.io.Serializable; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.security.Principal; import javax.servlet.http.HttpServletRequest; @@ -35,6 +38,7 @@ import org.apache.roller.weblogger.pojos.User; import org.apache.roller.weblogger.ui.core.security.AutoProvision; import org.apache.roller.weblogger.ui.core.security.OpenIdUrls; +import org.springframework.security.core.context.SecurityContextHolder; /** @@ -47,11 +51,24 @@ 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"; + + // 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); @@ -61,8 +78,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); @@ -70,10 +100,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); @@ -89,13 +127,8 @@ public static RollerSession getRollerSession(HttpServletRequest request) { try { UserManager umgr = WebloggerFactory.getWeblogger().getUserManager(); - User user = umgr.getUserByUserName(principal.getName()); - - // check for OpenID username (in the form of a URL) - if (user == null && OpenIdUrls.isOpenIdUrl(principal.getName())) { - user = umgr.getUserByOpenIdUrl(OpenIdUrls.normalize(principal.getName())); - } - + User user = findUser(umgr, principal); + // try one time to auto-provision, only happens if user==null // which means installation has LDAP enabled in security.xml if (user == null && WebloggerConfig.getBooleanProperty("users.ldap.autoProvision.enabled")) { @@ -112,9 +145,19 @@ 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) { log.error("ERROR: getting user object",e); } @@ -124,6 +167,204 @@ public static RollerSession getRollerSession(HttpServletRequest request) { return rollerSession; } + /** + * The enabled user a login belongs to, or null if there is none. + */ + private static User findUser(UserManager umgr, Principal principal) throws WebloggerException { + User user = umgr.getUserByUserName(principal.getName()); + + // check for OpenID username (in the form of a URL) + if (user == null && OpenIdUrls.isOpenIdUrl(principal.getName())) { + user = umgr.getUserByOpenIdUrl(OpenIdUrls.normalize(principal.getName())); + } + return user; + } + + /** + * Records a login in its session as soon as Spring Security accepts it: + * the user's password as it is now, so that a later password change ends + * the session even if Roller's pages are not opened in between. A login in + * a session that already had one replaces what that one left behind. + */ + public static void loggedIn(HttpServletRequest request, Principal login) { + try { + HttpSession session = request.getSession(true); + session.removeAttribute(ROLLER_SESSION); + session.removeAttribute(LOGIN_PASSWORD); + if (WebloggerFactory.isBootstrapped()) { + UserManager umgr = WebloggerFactory.getWeblogger().getUserManager(); + User user = findUser(umgr, login); + if (user != null) { + session.setAttribute(LOGIN_PASSWORD, user.getUserName() + "\n" + digest(user)); + } + } + } catch (WebloggerException e) { + log.error("ERROR: getting user object", e); + } + } + + /** + * Keeps the current session's other requests logged in while it saves a + * new password for its own user. Call it before the new password is + * saved, and refreshPassword after. + */ + public static void savingPassword(HttpServletRequest request, User user) { + HttpSession session = request != null ? request.getSession(false) : null; + if (session == null || user == null) { + return; + } + try { + Object attribute = session.getAttribute(ROLLER_SESSION); + if (attribute instanceof RollerSession + && user.getUserName().equals(((RollerSession) attribute).userName)) { + ((RollerSession) attribute).savingPasswordDigest = digest(user); + } + } catch (IllegalStateException e) { + if (!isInvalidated(session)) { + throw e; + } + // another request ended the session, there is no login to keep + } + } + + /** + * Keeps the current session logged in after its own user changed their + * password, or an administrator changed their own. Call it after the new + * 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 + && user.getUserName().equals(((RollerSession) attribute).userName)) { + ((RollerSession) attribute).setAuthenticatedUser(user); + ((RollerSession) attribute).savingPasswordDigest = null; + rememberLoginPassword(session, (RollerSession) attribute); + } + } 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) || !((String) recorded).startsWith(prefix)) { + return true; + } + return recorded.equals(prefix + digest(user)); + } + + private static void rememberLoginPassword(HttpSession session, RollerSession rollerSession) { + session.setAttribute(LOGIN_PASSWORD, rollerSession.userName + "\n" + rollerSession.passwordDigest); + } + + /** + * 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 + * is saving a new password for its user takes it on 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; + } + String current = digest(user); + if (current.equals(savingPasswordDigest)) { + passwordDigest = current; + savingPasswordDigest = null; + rememberLoginPassword(session, this); + } + return current.equals(passwordDigest); + } + + private static boolean isInvalidated(HttpSession session) { + 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) { + String password = user.getPassword() != null ? user.getPassword() : ""; + try { + MessageDigest sha = MessageDigest.getInstance("SHA-256"); + byte[] hash = sha.digest(password.getBytes(StandardCharsets.UTF_8)); + StringBuilder hex = new StringBuilder(hash.length * 2); + for (byte b : hash) { + hex.append(String.format("%02x", b)); + } + return hex.toString(); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 is required by the Java spec", e); + } + } + /** Create session's Roller instance */ @Override public void sessionCreated(HttpSessionEvent se) { @@ -171,6 +412,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 c0bf9705d..5fbf0675a 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilter.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilter.java @@ -22,6 +22,7 @@ import java.security.SecureRandom; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.RandomStringUtils; import org.apache.roller.weblogger.ui.core.RollerSession; import org.apache.roller.weblogger.ui.rendering.util.cache.SaltCache; @@ -32,6 +33,8 @@ */ public class LoadSaltFilter implements Filter { + private static final String ROLLER_UI_PATH = "/roller-ui/"; + /** Roller UI static files, which never hold a form. */ static final String[] STATIC_PATHS = {"/roller-ui/styles/", "/roller-ui/scripts/", "/roller-ui/images/", "/roller-ui/theme/"}; @@ -47,6 +50,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(); @@ -58,6 +64,36 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha chain.doFilter(request, response); } + /** + * Sends a request whose session Roller has just ended, because its user's + * password or account changed, back to the page it asked for, or to the + * login page if it posted a form. Spring Security then asks for a login + * where one is needed, as it does for any visitor who is not logged in. + * A weblog page forwarded here renders for a visitor who is not logged in. + * + * @return true when the request was redirected + */ + static boolean redirectEndedSession(HttpServletRequest request, HttpServletResponse response) + throws IOException { + if (!RollerSession.isSessionEnded(request) + || request.getDispatcherType() != DispatcherType.REQUEST) { + return false; + } + String 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; + } + /** Stylesheets, scripts and images get no session and no salt. */ static boolean isStaticFile(HttpServletRequest request) { String path = request.getServletPath(); 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 c0aa87f34..7b0f322af 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/filters/ValidateSaltFilter.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/filters/ValidateSaltFilter.java @@ -62,6 +62,10 @@ public void doFilter(ServletRequest request, ServletResponse response, try { SaltValidator.requireSubmittedSalt(httpReq); } catch (ServletException e) { + // the salt was issued to a login whose session just ended + if (LoadSaltFilter.redirectEndedSession(httpReq, (HttpServletResponse) response)) { + return; + } if (isPostTooLarge(httpReq)) { // The container dropped the form, salt included, because it // is over its maximum POST size. Pasted images make this diff --git a/app/src/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..2b984c7a3 --- /dev/null +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerLoginSuccessHandler.java @@ -0,0 +1,50 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.roller.weblogger.ui.core.security; + +import java.io.IOException; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.apache.roller.weblogger.ui.core.RollerSession; +import org.springframework.security.core.Authentication; +import org.springframework.security.web.authentication.AuthenticationSuccessHandler; + +/** + * Records a successful login in its session, then lets another handler send + * the user on. Roller ends a session when its user's password is no longer + * the one recorded here. + */ +public class RollerLoginSuccessHandler implements AuthenticationSuccessHandler { + + private final AuthenticationSuccessHandler next; + + public RollerLoginSuccessHandler(AuthenticationSuccessHandler next) { + this.next = next; + } + + @Override + public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, + Authentication authentication) throws IOException, ServletException { + RollerSession.loggedIn(request, authentication); + next.onAuthenticationSuccess(request, response, authentication); + } +} diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerRememberMeServices.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerRememberMeServices.java index 81042651f..2d3e9a1b1 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerRememberMeServices.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerRememberMeServices.java @@ -22,10 +22,14 @@ import org.apache.commons.logging.LogFactory; import org.apache.roller.weblogger.config.AuthMethod; import org.apache.roller.weblogger.config.WebloggerConfig; +import org.apache.roller.weblogger.ui.core.RollerSession; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.codec.Hex; import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices; +import javax.servlet.http.HttpServletRequest; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -49,6 +53,17 @@ public RollerRememberMeServices(UserDetailsService userDetailsService) { log.debug("initialized: RollerRememberMeServices with key"); } + /** + * Records the login a remember-me cookie stands for in its session, as a + * login form does. + */ + @Override + protected Authentication createSuccessfulAuthentication(HttpServletRequest request, UserDetails user) { + Authentication login = super.createSuccessfulAuthentication(request, user); + RollerSession.loggedIn(request, login); + return login; + } + /** * Calculates the digital signature to be put in the cookie. Default value is * SHA-512 ("username:tokenExpiryTime:password:key") diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/admin/UserEdit.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/admin/UserEdit.java index 90a2ef63d..97ca1973b 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/admin/UserEdit.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/admin/UserEdit.java @@ -24,6 +24,8 @@ import java.util.Locale; import java.util.TimeZone; +import javax.servlet.http.HttpServletRequest; + import org.apache.commons.lang3.CharSetUtils; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; @@ -38,8 +40,10 @@ import org.apache.roller.weblogger.pojos.User; import org.apache.roller.weblogger.pojos.WeblogPermission; import org.apache.roller.weblogger.ui.core.RollerLoginSessionManager; +import org.apache.roller.weblogger.ui.core.RollerSession; import org.apache.roller.weblogger.ui.struts2.core.Register; import org.apache.roller.weblogger.ui.struts2.util.UIAction; +import org.apache.struts2.interceptor.ServletRequestAware; import org.apache.roller.weblogger.ui.core.security.ExternalLoginAwarePasswordEncoder; import org.apache.struts2.interceptor.validation.SkipValidation; @@ -48,13 +52,15 @@ * Action that allows an admin to modify a users profile. */ // TODO: make this work @AllowedMethods({"execute","save","firstSave"}) -public class UserEdit extends UIAction { +public class UserEdit extends UIAction implements ServletRequestAware { private static Log log = LogFactory.getLog(UserEdit.class); // a bean to store our form data private CreateUserBean bean = new CreateUserBean(); + private HttpServletRequest servletRequest = null; + // user we are creating or modifying private User user = null; @@ -142,6 +148,7 @@ public String save() { myValidate(); if (!hasActionErrors()) { + String previousOpenIdUrl = user.getOpenIdUrl(); getBean().copyTo(user); if (authMethod == AuthMethod.DB_OPENID) { @@ -157,9 +164,14 @@ public String save() { } } - // User.password does not allow null, so generate one - if (authMethod.equals(AuthMethod.OPENID) || - (authMethod.equals(AuthMethod.DB_OPENID) && !StringUtils.isEmpty(bean.getOpenIdUrl()))) { + // User.password does not allow null, so generate one when the user + // starts signing in with an OpenID URL. Keep the stored one when the + // OpenID URL is unchanged, so an edit doesn't end the user's sessions. + if ((authMethod.equals(AuthMethod.OPENID) || + (authMethod.equals(AuthMethod.DB_OPENID) && !StringUtils.isEmpty(bean.getOpenIdUrl()))) + && (StringUtils.isEmpty(user.getPassword()) + || !StringUtils.equals(StringUtils.removeEnd(previousOpenIdUrl, "/"), + StringUtils.removeEnd(user.getOpenIdUrl(), "/")))) { String randomString = RandomStringUtils.randomAlphanumeric(255); user.resetPassword(randomString); } @@ -190,6 +202,9 @@ public String save() { // save new user mgr.addUser(user); } else { + if (isUserEditingSelf()) { + RollerSession.savingPassword(getServletRequest(), user); + } mgr.saveUser(user); } @@ -213,6 +228,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"); @@ -277,6 +298,15 @@ private void myValidate() { } } + protected HttpServletRequest getServletRequest() { + return servletRequest; + } + + @Override + public void setServletRequest(HttpServletRequest servletRequest) { + this.servletRequest = servletRequest; + } + public CreateUserBean getBean() { return bean; } diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/ajax/CommentDataServlet.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/ajax/CommentDataServlet.java index e1fc9d196..3dfb7b2d0 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/ajax/CommentDataServlet.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/ajax/CommentDataServlet.java @@ -64,7 +64,7 @@ public void doGet(HttpServletRequest request, // need post permission to view comments RollerSession rses = RollerSession.getRollerSession(request); Weblog weblog = c.getWeblogEntry().getWebsite(); - if (weblog.hasUserPermission(rses.getAuthenticatedUser(), WeblogPermission.POST)) { + if (hasPostPermission(rses, weblog)) { // HTML-escaped, since the page shows it as HTML String content = Utilities.escapeHTML(c.getContent()); String json = "{\"id\":\"" + StringEscapeUtils.escapeJson(c.getId()) @@ -105,7 +105,7 @@ public void doPut(HttpServletRequest request, // need post permission to edit comments RollerSession rses = RollerSession.getRollerSession(request); Weblog weblog = c.getWeblogEntry().getWebsite(); - if (weblog.hasUserPermission(rses.getAuthenticatedUser(), WeblogPermission.POST)) { + if (hasPostPermission(rses, weblog)) { String content = Utilities.streamToString(request.getInputStream()); c.setContent(content); // don't update the posttime when updating the comment @@ -137,6 +137,15 @@ public void doPost(HttpServletRequest request, doPut(request, response); } + /** + * Whether the session's user may post to the weblog. A request with no + * user, such as one whose session was just ended, may not. + */ + private static boolean hasPostPermission(RollerSession rses, Weblog weblog) { + return rses != null && rses.getAuthenticatedUser() != null + && weblog.hasUserPermission(rses.getAuthenticatedUser(), WeblogPermission.POST); + } + private void writeSaveResponse(HttpServletRequest request, HttpServletResponse response, int status, String id, String content) throws IOException { diff --git a/app/src/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 055cc5bef..d3c5c918f 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Profile.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Profile.java @@ -27,7 +27,9 @@ import org.apache.roller.weblogger.config.AuthMethod; import org.apache.roller.weblogger.config.WebloggerConfig; import org.apache.roller.weblogger.pojos.User; +import org.apache.roller.weblogger.ui.core.RollerSession; import org.apache.roller.weblogger.ui.struts2.util.UIAction; +import org.apache.struts2.interceptor.ServletRequestAware; import org.apache.roller.weblogger.ui.core.security.ExternalLoginAwarePasswordEncoder; import org.apache.struts2.interceptor.validation.SkipValidation; @@ -36,14 +38,18 @@ import java.util.Optional; import java.util.TimeZone; +import javax.servlet.http.HttpServletRequest; + /** * Allows user to edit his/her profile. */ // TODO: make this work @AllowedMethods({"execute","save"}) -public class Profile extends UIAction { +public class Profile extends UIAction implements ServletRequestAware { private static Log log = LogFactory.getLog(Profile.class); private ProfileBean bean = new ProfileBean(); + + private HttpServletRequest servletRequest = null; private AuthMethod authMethod = WebloggerConfig.getAuthMethod(); public Profile() { @@ -74,6 +80,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); @@ -105,9 +112,14 @@ public String save() { } } - // User.password does not allow null, so generate one - if (authMethod.equals(AuthMethod.OPENID) || - (authMethod.equals(AuthMethod.DB_OPENID) && !StringUtils.isEmpty(bean.getOpenIdUrl()))) { + // User.password does not allow null, so generate one when the user + // starts signing in with an OpenID URL. Keep the stored one when the + // OpenID URL is unchanged, so an edit doesn't end the user's sessions. + if ((authMethod.equals(AuthMethod.OPENID) || + (authMethod.equals(AuthMethod.DB_OPENID) && !StringUtils.isEmpty(bean.getOpenIdUrl()))) + && (StringUtils.isEmpty(existingUser.getPassword()) + || !StringUtils.equals(StringUtils.removeEnd(previousOpenIdUrl, "/"), + StringUtils.removeEnd(existingUser.getOpenIdUrl(), "/")))) { String randomString = RandomStringUtils.randomAlphanumeric(255); existingUser.resetPassword(randomString); } @@ -120,9 +132,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) { @@ -181,6 +196,15 @@ public void myValidate() { } } + protected HttpServletRequest getServletRequest() { + return servletRequest; + } + + @Override + public void setServletRequest(HttpServletRequest servletRequest) { + this.servletRequest = servletRequest; + } + public String getAuthMethod() { return authMethod.name(); } diff --git a/app/src/main/webapp/WEB-INF/security.xml b/app/src/main/webapp/WEB-INF/security.xml index 18ed9206a..2d31c47f2 100644 --- a/app/src/main/webapp/WEB-INF/security.xml +++ b/app/src/main/webapp/WEB-INF/security.xml @@ -41,6 +41,7 @@ username-parameter="j_username" password-parameter="j_password" authentication-failure-url="/roller-ui/login.rol?error=true" + authentication-success-handler-ref="formLoginSuccessHandler" login-processing-url="/roller_j_security_check"/> + + + + + + + - + class="org.apache.roller.weblogger.ui.core.security.RollerLoginSuccessHandler"> + + + + + bean.setPassword("reset-password")); + + b.assertLoggedOut(); + admin.assertLoggedIn(adminName); + } + + @Test + void disablingAUserEndsTheirSessions() throws Exception { + Browser admin = new Browser(adminName); + Browser b = new Browser(userName); + admin.request(); + assertEquals(userName, b.request().getAuthenticatedUser().getUserName()); + TestUtils.endSession(true); + + saveAsAdmin(admin, bean -> bean.setEnabled(false)); + + b.assertLoggedOut(); + admin.assertLoggedIn(adminName); + } + + @Test + void disablingAUserEndsTheirOpenIdSessions() throws Exception { + // OpenID 2.0 logins carry the user's OpenID URL as the principal name + String openIdUrl = "https://openid.example.com/sessionuser"; + UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); + User u = user(userName); + u.setOpenIdUrl(openIdUrl); + mgr.saveUser(u); + TestUtils.endSession(true); + + Browser admin = new Browser(adminName); + Browser b = new Browser(openIdUrl + "/"); + admin.request(); + assertEquals(userName, b.request().getAuthenticatedUser().getUserName()); + TestUtils.endSession(true); + + saveAsAdmin(admin, bean -> bean.setEnabled(false)); + + b.assertLoggedOut(); + admin.assertLoggedIn(adminName); + } + + @Test + void adminChangingOwnPasswordStaysLoggedIn() throws Exception { + Browser admin = new Browser(adminName); + Browser other = new Browser(adminName); + admin.request(); + other.request(); + TestUtils.endSession(true); + + admin.request(); + UserEdit action = userEdit(admin, adminName); + action.getBean().setPassword("reset-password"); + assertEquals(UserEdit.SUCCESS, action.save()); + TestUtils.endSession(true); + + other.assertLoggedOut(); + admin.assertLoggedIn(adminName); + } + + @Test + void savingWithoutAPasswordChangeKeepsOtherSessions() throws Exception { + Browser admin = new Browser(adminName); + Browser b = new Browser(userName); + admin.request(); + b.request(); + TestUtils.endSession(true); + + saveAsAdmin(admin, bean -> bean.setFullName("Renamed User")); + + b.assertLoggedIn(userName); + } + + @Test + void openIdProfileEditKeepsTheUsersOtherSessions() throws Exception { + linkOpenId(userName, "https://openid.example.com/sessionuser"); + Browser a = new Browser(userName); + Browser b = new Browser(userName); + a.request(); + b.request(); + TestUtils.endSession(true); + String storedPassword = user(userName).getPassword(); + + a.request(); + Profile profile = spy(new Profile()); + stubText(profile); + setAuthMethod(profile, AuthMethod.OPENID); + User self = user(userName); + ProfileBean bean = new ProfileBean(); + bean.copyFrom(self); + bean.setScreenName("Renamed"); + profile.setBean(bean); + profile.setAuthenticatedUser(self); + profile.setServletRequest(a.httpRequest); + assertEquals(Profile.SUCCESS, profile.save(), () -> String.valueOf(profile.getActionErrors())); + TestUtils.endSession(true); + + assertEquals("Renamed", user(userName).getScreenName()); + assertEquals(storedPassword, user(userName).getPassword()); + b.assertLoggedIn(userName); + a.assertLoggedIn(userName); + } + + @Test + void adminEditOfAnOpenIdUserKeepsTheirSessions() throws Exception { + linkOpenId(userName, "https://openid.example.com/sessionuser"); + Browser admin = new Browser(adminName); + Browser b = new Browser(userName); + admin.request(); + b.request(); + TestUtils.endSession(true); + String storedPassword = user(userName).getPassword(); + + admin.request(); + UserEdit action = userEdit(admin, userName); + setAuthMethod(action, AuthMethod.DB_OPENID); + action.getBean().setFullName("Renamed User"); + assertEquals(UserEdit.SUCCESS, action.save(), () -> String.valueOf(action.getActionErrors())); + TestUtils.endSession(true); + + assertEquals(storedPassword, user(userName).getPassword()); + b.assertLoggedIn(userName); + } + + @Test + void switchingToOpenIdReplacesTheStoredPassword() throws Exception { + Browser admin = new Browser(adminName); + Browser b = new Browser(userName); + admin.request(); + b.request(); + TestUtils.endSession(true); + String storedPassword = user(userName).getPassword(); + + admin.request(); + UserEdit action = userEdit(admin, userName); + setAuthMethod(action, AuthMethod.DB_OPENID); + action.getBean().setOpenIdUrl("https://openid.example.com/sessionuser"); + assertEquals(UserEdit.SUCCESS, action.save(), () -> String.valueOf(action.getActionErrors())); + TestUtils.endSession(true); + + assertNotEquals(storedPassword, user(userName).getPassword()); + b.assertLoggedOut(); + } + + private static void linkOpenId(String name, String openIdUrl) throws Exception { + UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); + User u = mgr.getUserByUserName(name, null); + u.setOpenIdUrl(openIdUrl); + mgr.saveUser(u); + TestUtils.endSession(true); + } + + private static void setAuthMethod(Object action, AuthMethod method) throws Exception { + // the action is a Mockito spy, a subclass of the real action + Field field = findField(action.getClass(), "authMethod"); + field.setAccessible(true); + field.set(action, method); + } + + private static Field findField(Class type, String name) throws NoSuchFieldException { + for (Class c = type; c != null; c = c.getSuperclass()) { + try { + return c.getDeclaredField(name); + } catch (NoSuchFieldException ignored) { + // keep looking in the superclass + } + } + throw new NoSuchFieldException(name); + } + + @Test + void passwordChangeEndsASessionThatWasPassivated() throws Exception { + Browser a = new Browser(userName); + Browser b = new Browser(userName); + a.request(); + b.request(); + TestUtils.endSession(true); + + // the container saves b's session and restores it later, which drops + // the Roller session but keeps the login + b.passivate(); + + a.request(); + Profile profile = spy(new Profile()); + stubText(profile); + User self = user(userName); + ProfileBean bean = new ProfileBean(); + bean.copyFrom(self); + bean.setPasswordText("changed-password"); + bean.setPasswordConfirm("changed-password"); + profile.setBean(bean); + profile.setAuthenticatedUser(self); + profile.setServletRequest(a.httpRequest); + assertEquals(Profile.SUCCESS, profile.save()); + TestUtils.endSession(true); + + b.assertLoggedOut(); + // the session that changed the password keeps working after a restore + a.passivate(); + a.assertLoggedIn(userName); + } + + @Test + void passivatedSessionStaysLoggedInWithoutAPasswordChange() throws Exception { + Browser b = new Browser(userName); + b.request(); + TestUtils.endSession(true); + + b.passivate(); + + b.assertLoggedIn(userName); + } + + @Test + void passwordChangeEndsALoginThatHasNotOpenedTheUiYet() throws Exception { + Browser a = new Browser(userName); + // b logged in and went to a weblog page, so Roller has not looked at + // its session yet + Browser b = new Browser(userName); + a.request(); + TestUtils.endSession(true); + + changeOwnPassword(a); + + b.assertLoggedOut(); + a.assertLoggedIn(userName); + } + + @Test + void passwordChangeEndsARememberMeLoginThatHasNotOpenedTheUiYet() throws Exception { + Browser a = new Browser(userName); + Browser b = Browser.remembered(userName); + a.request(); + TestUtils.endSession(true); + + changeOwnPassword(a); + + b.assertLoggedOut(); + a.assertLoggedIn(userName); + } + + @Test + void passwordChangeEndsAnOpenIdLoginThatHasNotOpenedTheUiYet() throws Exception { + // OpenID 2.0 logins carry the user's OpenID URL as the principal name + String openIdUrl = "https://openid.example.com/sessionuser"; + linkOpenId(userName, openIdUrl); + Browser admin = new Browser(adminName); + Browser b = new Browser(openIdUrl + "/"); + admin.request(); + TestUtils.endSession(true); + + saveAsAdmin(admin, bean -> bean.setPassword("reset-password")); + + b.assertLoggedOut(); + } + + @Test + void disablingAUserEndsALoginThatHasNotOpenedTheUiYet() throws Exception { + Browser admin = new Browser(adminName); + Browser b = new Browser(userName); + admin.request(); + TestUtils.endSession(true); + + saveAsAdmin(admin, bean -> bean.setEnabled(false)); + + b.assertLoggedOut(); + admin.assertLoggedIn(adminName); + } + + @Test + void disablingAUserEndsASessionThatWasPassivated() throws Exception { + Browser admin = new Browser(adminName); + Browser b = new Browser(userName); + admin.request(); + b.request(); + TestUtils.endSession(true); + b.passivate(); + + saveAsAdmin(admin, bean -> bean.setEnabled(false)); + + b.assertLoggedOut(); + } + + @Test + void removingAUserEndsALoginThatHasNotOpenedTheUiYet() throws Exception { + String goneName = TestUtils.setupUser("sessiongone").getUserName(); + TestUtils.endSession(true); + Browser b = new Browser(goneName); + + TestUtils.teardownUser(goneName); + TestUtils.endSession(true); + + b.assertLoggedOut(); + } + + @Test + void loggingInAgainInAStaleSessionStaysLoggedIn() throws Exception { + Browser a = new Browser(userName); + Browser b = new Browser(userName); + a.request(); + b.request(); + TestUtils.endSession(true); + + changeOwnPassword(a); + + // b still has its old session and logs in again with the new + // password before making any other request + b.login(); + b.assertLoggedIn(userName); + a.assertLoggedIn(userName); + } + + @Test + void loggingInAsAnotherUserInTheSameSessionSwitchesUser() throws Exception { + Browser b = new Browser(userName); + assertEquals(userName, b.request().getAuthenticatedUser().getUserName()); + TestUtils.endSession(true); + + b.login(UsernamePasswordAuthenticationToken.authenticated(adminName, null, List.of())); + + b.assertLoggedIn(adminName); + } + + @Test + void requestOnASessionEndedByAnotherRequestIsLoggedOut() throws Exception { + Browser b = new Browser(userName); + b.request(); + TestUtils.endSession(true); + + b.sessionEndsDuringNextRequest(); + + b.assertLoggedOut(); + } + + @Test + void endingASessionLogsOutItsParallelRequests() throws Exception { + Browser a = new Browser(userName); + Browser b = new Browser(userName); + a.request(); + b.request(); + TestUtils.endSession(true); + + changeOwnPassword(a); + + // Spring gives two requests of b the login context kept in b's session + SecurityContext shared = SecurityContextHolder.createEmptyContext(); + shared.setAuthentication(b.login); + HttpServletRequest parallel = b.requestWith(shared); + + // the first one ends the session + SecurityContextHolder.setContext(shared); + RollerSession.getRollerSession(b.httpRequest); + + // the second one asks for a session afterwards, as LoadSaltFilter does + SecurityContextHolder.setContext(shared); + parallel.getSession(true); + RollerSession rollerSession = RollerSession.getRollerSession(parallel); + + assertNull(rollerSession.getAuthenticatedUser(), "the parallel request should have no user"); + assertNull(shared.getAuthentication(), "the login should be cleared for every request of the session"); + a.assertLoggedIn(userName); + } + + @Test + void ownRequestWhilePasswordIsSavedStaysLoggedIn() throws Exception { + Browser a = new Browser(userName); + Browser b = new Browser(userName); + a.request(); + b.request(); + TestUtils.endSession(true); + + // what Profile.save does, with another request of a in between the + // commit and the end of the save + a.request(); + User self = user(userName); + self.resetPassword("changed-password"); + RollerSession.savingPassword(a.httpRequest, self); + WebloggerFactory.getWeblogger().getUserManager().saveUser(self); + WebloggerFactory.getWeblogger().flush(); + a.assertLoggedIn(userName); + RollerSession.refreshPassword(a.httpRequest, self); + TestUtils.endSession(true); + + a.assertLoggedIn(userName); + b.assertLoggedOut(); + } + + @Test + void savingAProfileOnASessionEndedByAnotherRequestDoesNotFail() throws Exception { + Browser b = new Browser(userName); + b.request(); + TestUtils.endSession(true); + + b.sessionEndsDuringNextRequest(); + + assertDoesNotThrow(() -> RollerSession.refreshPassword(b.httpRequest, user(userName))); + } + + @Test + void openIdProfileEditKeepsSessionsWhenTheStoredUrlEndsWithASlash() throws Exception { + linkOpenId(userName, "https://openid.example.com/sessionuser/"); + Browser a = new Browser(userName); + Browser b = new Browser(userName); + a.request(); + b.request(); + TestUtils.endSession(true); + String storedPassword = user(userName).getPassword(); + + a.request(); + Profile profile = spy(new Profile()); + stubText(profile); + setAuthMethod(profile, AuthMethod.OPENID); + User self = user(userName); + ProfileBean bean = new ProfileBean(); + bean.copyFrom(self); + bean.setScreenName("Renamed"); + profile.setBean(bean); + profile.setAuthenticatedUser(self); + profile.setServletRequest(a.httpRequest); + assertEquals(Profile.SUCCESS, profile.save(), () -> String.valueOf(profile.getActionErrors())); + TestUtils.endSession(true); + + assertEquals(storedPassword, user(userName).getPassword()); + b.assertLoggedIn(userName); + a.assertLoggedIn(userName); + } + + @Test + void adminEditKeepsSessionsWhenOnlyATrailingSlashIsAdded() throws Exception { + linkOpenId(userName, "https://openid.example.com/sessionuser"); + Browser admin = new Browser(adminName); + Browser b = new Browser(userName); + admin.request(); + b.request(); + TestUtils.endSession(true); + String storedPassword = user(userName).getPassword(); + + admin.request(); + UserEdit action = userEdit(admin, userName); + setAuthMethod(action, AuthMethod.DB_OPENID); + action.getBean().setOpenIdUrl("https://openid.example.com/sessionuser/"); + assertEquals(UserEdit.SUCCESS, action.save(), () -> String.valueOf(action.getActionErrors())); + TestUtils.endSession(true); + + assertEquals(storedPassword, user(userName).getPassword()); + b.assertLoggedIn(userName); + } + + /** The user of this browser changes their own password on the profile page. */ + private void changeOwnPassword(Browser a) throws Exception { + a.request(); + Profile profile = spy(new Profile()); + stubText(profile); + User self = user(a.login.getName()); + ProfileBean bean = new ProfileBean(); + bean.copyFrom(self); + bean.setPasswordText("changed-password"); + bean.setPasswordConfirm("changed-password"); + profile.setBean(bean); + profile.setAuthenticatedUser(self); + profile.setServletRequest(a.httpRequest); + assertEquals(Profile.SUCCESS, profile.save(), () -> String.valueOf(profile.getActionErrors())); + TestUtils.endSession(true); + } + + private void saveAsAdmin(Browser admin, java.util.function.Consumer change) + throws Exception { + admin.request(); + UserEdit action = userEdit(admin, userName); + change.accept(action.getBean()); + assertEquals(UserEdit.SUCCESS, action.save()); + TestUtils.endSession(true); + } + + private UserEdit userEdit(Browser admin, String target) throws Exception { + UserEdit action = spy(new UserEdit()); + stubText(action); + action.setActionName("modifyUser"); + action.setAuthenticatedUser(user(adminName)); + action.setServletRequest(admin.httpRequest); + action.getBean().setId(user(target).getId()); + action.myPrepare(); + action.getBean().copyFrom(user(target)); + action.getBean().setPassword(null); + return action; + } + + private static void stubText(org.apache.roller.weblogger.ui.struts2.util.UIAction action) { + doAnswer(call -> call.getArgument(0)).when(action).getText(anyString()); + doAnswer(call -> call.getArgument(0)).when(action).getText(anyString(), anyString()); + doAnswer(call -> call.getArgument(0)).when(action).getText(anyString(), anyList()); + } + + private static User user(String name) throws Exception { + UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); + return mgr.getUserByUserName(name, null); + } + + private static PasswordEncoder swapEncoder(PasswordEncoder encoder) throws Exception { + Field field = RollerContext.class.getDeclaredField("encoder"); + field.setAccessible(true); + PasswordEncoder previous = (PasswordEncoder) field.get(null); + field.set(null, encoder); + return previous; + } + + /** + * One browser: an HTTP session and the Spring login stored in it. Each + * request puts that login in the SecurityContextHolder, as Spring does, + * while the session holding it is still valid. + */ + private static final class Browser { + final HttpServletRequest httpRequest = mock(HttpServletRequest.class); + Authentication login; + HttpSession session; + // the session holding the login was invalidated + boolean ended; + // a session another request invalidated after this one picked it up + HttpSession endedUnderneath; + // attributes of the current request + final Map requestAttributes = new HashMap<>(); + + Browser(String name) { + this(UsernamePasswordAuthenticationToken.authenticated(name, null, List.of())); + } + + Browser(Authentication authentication) { + this(authentication, false); + } + + private Browser(Authentication authentication, boolean remembered) { + session = newSession(); + // keep reporting the login, so a rebuild from it would show + when(httpRequest.getUserPrincipal()).thenAnswer(call -> login); + when(httpRequest.getSession(false)).thenAnswer(call -> { + if (endedUnderneath != null) { + HttpSession stale = endedUnderneath; + endedUnderneath = null; + return stale; + } + return session; + }); + when(httpRequest.getSession(true)).thenAnswer(call -> { + if (session == null) { + session = newSession(); + } + return session; + }); + when(httpRequest.getSession()).thenAnswer(call -> httpRequest.getSession(true)); + doAnswer(call -> requestAttributes.put(call.getArgument(0), call.getArgument(1))) + .when(httpRequest).setAttribute(anyString(), any()); + when(httpRequest.getAttribute(anyString())) + .thenAnswer(call -> requestAttributes.get(call.getArgument(0))); + if (remembered) { + rememberMeLogin(authentication.getName()); + } else { + login(authentication); + } + } + + /** A browser whose remember-me cookie logged it in. */ + static Browser remembered(String name) { + return new Browser(UsernamePasswordAuthenticationToken.authenticated(name, null, List.of()), true); + } + + /** Logs in again with the same account, in the session it has. */ + void login() { + login(login); + } + + /** Spring authenticated a login form or an OpenID sign-in. */ + void login(Authentication authentication) { + login = authentication; + ended = false; + try { + new RollerLoginSuccessHandler((request, response, auth) -> { }) + .onAuthenticationSuccess(httpRequest, mock(HttpServletResponse.class), login); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + /** Spring accepted the browser's remember-me cookie. */ + private void rememberMeLogin(String name) { + UserDetails details = org.springframework.security.core.userdetails.User + .withUsername(name).password("stored-hash").authorities(List.of()).build(); + login = new RollerRememberMeServices(userName -> details) { + Authentication accept() { + return createSuccessfulAuthentication(httpRequest, details); + } + }.accept(); + } + + /** + * Another request of this browser, which reads its login from the + * given security context, as Spring's request wrapper does. + */ + HttpServletRequest requestWith(SecurityContext context) { + HttpServletRequest other = mock(HttpServletRequest.class); + when(other.getUserPrincipal()).thenAnswer(call -> context.getAuthentication()); + when(other.getSession(false)).thenAnswer(call -> httpRequest.getSession(false)); + when(other.getSession(true)).thenAnswer(call -> httpRequest.getSession(true)); + when(other.getSession()).thenAnswer(call -> httpRequest.getSession(true)); + return other; + } + + /** + * Another request of this browser ends the session just after the + * next request has picked it up. + */ + void sessionEndsDuringNextRequest() { + HttpSession current = session; + current.invalidate(); + endedUnderneath = current; + } + + 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); + attributes.remove(call.getArgument(0)); + return null; + }).when(s).removeAttribute(anyString()); + when(s.getCreationTime()).thenAnswer(call -> { + checkValid(valid); + return 0L; + }); + doAnswer(call -> { + checkValid(valid); + valid[0] = false; + 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"); + } + } + + /** The container saves this session and restores it later. */ + void passivate() { + new RollerSession().sessionWillPassivate(new HttpSessionEvent(session)); + } + + RollerSession request() { + requestAttributes.clear(); + if (ended && endedUnderneath == null) { + 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"); + assertTrue(RollerSession.isSessionEnded(httpRequest), "the request should be marked as logged out"); + assertNull(SecurityContextHolder.getContext().getAuthentication(), + "the login should be cleared from this request"); + SecurityContextHolder.clearContext(); + } + + 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"); + assertFalse(RollerSession.isSessionEnded(httpRequest)); + assertNotNull(SecurityContextHolder.getContext().getAuthentication()); + SecurityContextHolder.clearContext(); + } + } +} diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilterTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilterTest.java index 71e8b8705..3fcc9fa9c 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilterTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/LoadSaltFilterTest.java @@ -9,6 +9,7 @@ import org.mockito.MockedStatic; import org.mockito.MockitoAnnotations; +import javax.servlet.DispatcherType; import javax.servlet.FilterChain; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -74,6 +75,76 @@ public void testDoFilterWithNullRollerSession() throws Exception { } } + @Test + void requestWhoseSessionWasEndedGoesBackToThePageItAskedFor() throws Exception { + try (MockedStatic mockedRollerSession = mockStatic(RollerSession.class)) { + mockedRollerSession.when(() -> RollerSession.getRollerSession(request)).thenReturn(rollerSession); + mockedRollerSession.when(() -> RollerSession.isSessionEnded(request)).thenReturn(true); + when(request.getDispatcherType()).thenReturn(DispatcherType.REQUEST); + when(request.getMethod()).thenReturn("GET"); + when(request.getContextPath()).thenReturn("/roller"); + when(request.getServletPath()).thenReturn("/roller-ui/menu.rol"); + when(request.getQueryString()).thenReturn("weblog=demo"); + + filter.doFilter(request, response, chain); + + verify(response).sendRedirect("/roller/roller-ui/menu.rol?weblog=demo"); + verify(chain, never()).doFilter(request, response); + } + } + + @Test + void endedSessionOutsideTheAdminUiGoesToTheLoginPage() throws Exception { + try (MockedStatic mockedRollerSession = mockStatic(RollerSession.class)) { + mockedRollerSession.when(() -> RollerSession.getRollerSession(request)).thenReturn(rollerSession); + mockedRollerSession.when(() -> RollerSession.isSessionEnded(request)).thenReturn(true); + when(request.getDispatcherType()).thenReturn(DispatcherType.REQUEST); + when(request.getMethod()).thenReturn("GET"); + // Roller deployed at the root, and a path that a browser reads as a host + when(request.getContextPath()).thenReturn(""); + when(request.getServletPath()).thenReturn(""); + when(request.getPathInfo()).thenReturn("//example.com/page"); + + filter.doFilter(request, response, chain); + + verify(response).sendRedirect("/roller-ui/login.rol"); + verify(chain, never()).doFilter(request, response); + } + } + + @Test + void formPostWhoseSessionWasEndedGoesToTheLoginPage() throws Exception { + try (MockedStatic mockedRollerSession = mockStatic(RollerSession.class)) { + mockedRollerSession.when(() -> RollerSession.getRollerSession(request)).thenReturn(rollerSession); + mockedRollerSession.when(() -> RollerSession.isSessionEnded(request)).thenReturn(true); + when(request.getDispatcherType()).thenReturn(DispatcherType.REQUEST); + when(request.getMethod()).thenReturn("POST"); + when(request.getContextPath()).thenReturn("/roller"); + + filter.doFilter(request, response, chain); + + verify(response).sendRedirect("/roller/roller-ui/login.rol"); + verify(chain, never()).doFilter(request, response); + } + } + + @Test + void weblogPageWhoseSessionWasEndedStillRenders() throws Exception { + try (MockedStatic mockedRollerSession = mockStatic(RollerSession.class); + MockedStatic mockedSaltCache = mockStatic(SaltCache.class)) { + mockedRollerSession.when(() -> RollerSession.getRollerSession(request)).thenReturn(rollerSession); + mockedRollerSession.when(() -> RollerSession.isSessionEnded(request)).thenReturn(true); + mockedSaltCache.when(SaltCache::getInstance).thenReturn(saltCache); + // weblog pages are forwarded to the rendering servlets + when(request.getDispatcherType()).thenReturn(DispatcherType.FORWARD); + + filter.doFilter(request, response, chain); + + verify(response, never()).sendRedirect(anyString()); + verify(chain).doFilter(request, response); + } + } + @Test void firstFormHasAUsableSalt() throws Exception { javax.servlet.http.HttpSession session = mock(javax.servlet.http.HttpSession.class); diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/ValidateSaltFilterTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/ValidateSaltFilterTest.java index f312ffc0c..398677290 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/ValidateSaltFilterTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/filters/ValidateSaltFilterTest.java @@ -9,6 +9,7 @@ import org.mockito.MockedStatic; import org.mockito.MockitoAnnotations; +import javax.servlet.DispatcherType; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; @@ -87,6 +88,28 @@ public void testDoFilterWithPostMethodAndInvalidSalt() throws Exception { } } + @Test + void formPostWhoseSessionWasEndedGoesToTheLoginPage() throws Exception { + try (MockedStatic mockedRollerSession = mockStatic(RollerSession.class); + MockedStatic mockedSaltCache = mockStatic(SaltCache.class)) { + + // the session ended, so the form's salt belongs to its old user + mockedRollerSession.when(() -> RollerSession.getRollerSession(request)).thenReturn(rollerSession); + mockedRollerSession.when(() -> RollerSession.isSessionEnded(request)).thenReturn(true); + mockedSaltCache.when(SaltCache::getInstance).thenReturn(saltCache); + when(request.getDispatcherType()).thenReturn(DispatcherType.REQUEST); + when(request.getMethod()).thenReturn("POST"); + when(request.getContextPath()).thenReturn("/roller"); + when(request.getParameter("salt")).thenReturn("oldSalt"); + when(saltCache.get("oldSalt")).thenReturn("userId"); + + filter.doFilter(request, response, chain); + + verify(response).sendRedirect("/roller/roller-ui/login.rol"); + verify(chain, never()).doFilter(request, response); + } + } + @Test public void testPostTooLargeForTheContainerGetsA413() throws Exception { try (MockedStatic mockedRollerSession = mockStatic(RollerSession.class)) { diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/security/SecurityXmlLoginWiringTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/security/SecurityXmlLoginWiringTest.java new file mode 100644 index 000000000..7ab31d1bc --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/security/SecurityXmlLoginWiringTest.java @@ -0,0 +1,112 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.roller.weblogger.ui.core.security; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; + +import org.apache.roller.weblogger.TestUtils; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.context.support.GenericXmlApplicationContext; +import org.springframework.core.io.FileSystemResource; +import org.springframework.security.web.FilterChainProxy; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Every way of logging in that security.xml sets up records the login in its + * session, which is what lets a later password change end that session. + */ +class SecurityXmlLoginWiringTest { + + private static GenericXmlApplicationContext context; + private static final List filters = new ArrayList<>(); + + @BeforeAll + static void loadSecurityXml() throws Exception { + TestUtils.setupWeblogger(); + context = new GenericXmlApplicationContext( + new FileSystemResource("src/main/webapp/WEB-INF/security.xml")); + for (SecurityFilterChain chain : context.getBean(FilterChainProxy.class).getFilterChains()) { + filters.addAll(chain.getFilters()); + } + } + + @AfterAll + static void close() { + if (context != null) { + context.close(); + } + } + + @Test + void formLoginRecordsTheLogin() throws Exception { + long formLogins = 0; + for (Object filter : filters) { + if (filter instanceof UsernamePasswordAuthenticationFilter) { + formLogins++; + assertInstanceOf(RollerLoginSuccessHandler.class, successHandler(filter)); + } + } + assertEquals(1, formLogins, "security.xml should set up one form login"); + } + + @Test + void everyLoginFilterRecordsTheLogin() throws Exception { + long loginFilters = 0; + for (Object filter : filters) { + if (filter instanceof AbstractAuthenticationProcessingFilter) { + loginFilters++; + assertInstanceOf(RollerLoginSuccessHandler.class, successHandler(filter), + filter.getClass().getSimpleName() + " should record the login"); + } + } + // the login form and single sign-on + assertTrue(loginFilters >= 2, "expected the form and single sign-on filters, found " + loginFilters); + } + + @Test + void rememberMeRecordsTheLogin() { + long rememberMeFilters = 0; + for (Object filter : filters) { + if (filter instanceof RememberMeAuthenticationFilter) { + rememberMeFilters++; + assertInstanceOf(RollerRememberMeServices.class, + ((RememberMeAuthenticationFilter) filter).getRememberMeServices()); + } + } + assertEquals(1, rememberMeFilters, "security.xml should set up remember-me"); + } + + private static Object successHandler(Object filter) throws Exception { + Field field = AbstractAuthenticationProcessingFilter.class.getDeclaredField("successHandler"); + field.setAccessible(true); + return field.get(filter); + } +} diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/ajax/CommentDataServletTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/ajax/CommentDataServletTest.java index 8efda9cef..91b21f645 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/ajax/CommentDataServletTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/ajax/CommentDataServletTest.java @@ -94,6 +94,38 @@ public void testGetReturnsJson() throws Exception { json.get("content").asText()); } + @Test + public void testGetWithoutAUserIsForbidden() throws Exception { + Weblogger weblogger = mock(Weblogger.class); + WeblogEntryManager manager = mock(WeblogEntryManager.class); + WeblogEntryComment comment = mock(WeblogEntryComment.class); + WeblogEntry entry = mock(WeblogEntry.class); + Weblog weblog = mock(Weblog.class); + // a session that was just ended has no user + RollerSession session = mock(RollerSession.class); + + when(weblogger.getWeblogEntryManager()).thenReturn(manager); + when(manager.getComment("comment-id")).thenReturn(comment); + when(comment.getWeblogEntry()).thenReturn(entry); + when(entry.getWebsite()).thenReturn(weblog); + // as Weblog does, which builds a permission from the user + when(weblog.hasUserPermission(null, WeblogPermission.POST)).thenThrow(new NullPointerException()); + + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getParameter("id")).thenReturn("comment-id"); + HttpServletResponse response = mock(HttpServletResponse.class); + + try (MockedStatic factory = mockStatic(WebloggerFactory.class); + MockedStatic sessions = mockStatic(RollerSession.class)) { + factory.when(WebloggerFactory::getWeblogger).thenReturn(weblogger); + sessions.when(() -> RollerSession.getRollerSession(request)).thenReturn(session); + + new CommentDataServlet().doGet(request, response); + } + + verify(response).setStatus(HttpServletResponse.SC_FORBIDDEN); + } + @Test public void testRepeatedSavesReturnFreshResponseSalts() throws Exception { Weblogger weblogger = mock(Weblogger.class);