diff --git a/CHANGES.md b/CHANGES.md index b2240dc961..bcb8feb8e3 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -83,8 +83,10 @@ - **Tags of a scheduled entry are counted once, when it goes live.** Entries posted through AtomPub with a future date showed their tags in tag counts early and counted them twice (#316). -- **A weblog's only administrator can't resign from it**, and declining an - invitation only removes a pending invitation (#322). +- **A weblog's only administrator can't resign from it**, and the main menu + says why. After resigning, the main menu now shows whether it worked. + Declining an invitation only removes a pending invitation, and declining + one you already accepted says you're already a member (#322). - **Passwords stored with an older encoding are upgraded at login.** With `passwds.encryption.lazyUpgradeFrom` set (`SHA` by default), passwords from older Roller versions could be used to log in, but they stayed stored in the @@ -203,8 +205,8 @@ permission to publish, media uploads over `uploads.file.maxsize` are refused with 413 before they're stored, and entries show the creator's email address only to the creator (also in MetaWeblog responses) (#316). -- **Search queries are limited to 256 characters**, and a query the search - engine can't run finds nothing (#322). +- **Search queries are limited to 256 characters**, after spaces around them + are dropped, and a query the search engine can't run finds nothing (#322). - **The OpenID Connect identity can't be changed from the profile or registration forms**; only Roller's OpenID Connect login sets it (#322). - **Weblog pages ignore a `skipCache` query parameter** (#313). diff --git a/app/src/main/java/org/apache/roller/weblogger/business/UserManager.java b/app/src/main/java/org/apache/roller/weblogger/business/UserManager.java index 905087f53a..dfe94b2df1 100644 --- a/app/src/main/java/org/apache/roller/weblogger/business/UserManager.java +++ b/app/src/main/java/org/apache/roller/weblogger/business/UserManager.java @@ -283,6 +283,21 @@ List getWeblogPermissions(Weblog weblog) List getPendingWeblogPermissions(Weblog weblog) throws WebloggerException; + /** + * Change the memberships of a weblog as one operation that keeps the + * weblog's administrators. Changes for the same weblog are serialized: + * the weblog's row stays locked until the caller flushes or releases the + * session, so the administrator check and the changes cannot interleave + * with another membership update. + * @param weblog Weblog whose memberships change + * @param changes New actions by user name; a null value removes that + * user's membership + * @return false, with nothing changed, if the changes would remove the + * weblog's last administrator (pending invitations don't count) + */ + boolean updateWeblogMembership(Weblog weblog, Map> changes) + throws WebloggerException; + /** * Get all permissions (pending or actual) for a weblog. */ diff --git a/app/src/main/java/org/apache/roller/weblogger/business/jpa/JPAUserManagerImpl.java b/app/src/main/java/org/apache/roller/weblogger/business/jpa/JPAUserManagerImpl.java index 78a578c117..f79fdb03d5 100644 --- a/app/src/main/java/org/apache/roller/weblogger/business/jpa/JPAUserManagerImpl.java +++ b/app/src/main/java/org/apache/roller/weblogger/business/jpa/JPAUserManagerImpl.java @@ -33,7 +33,10 @@ import java.util.List; import java.util.Map; import java.util.TreeMap; +import jakarta.persistence.EntityManager; +import jakarta.persistence.LockModeType; import jakarta.persistence.NoResultException; +import jakarta.persistence.PersistenceException; import jakarta.persistence.TypedQuery; import org.apache.roller.weblogger.config.WebloggerConfig; import org.apache.roller.weblogger.pojos.GlobalPermission; @@ -78,7 +81,10 @@ public void removeUser(User user) throws WebloggerException { String userName = user.getUserName(); // remove permissions, maintaining both sides of relationship - List perms = getWeblogPermissions(user); + List perms = new ArrayList<>(getWeblogPermissions(user)); + // and pending invitations, which a new user of the same name would + // otherwise inherit + perms.addAll(getPendingWeblogPermissions(user)); for (WeblogPermission perm : perms) { this.strategy.remove(perm); } @@ -514,6 +520,10 @@ public void declineWeblogPermission(Weblog weblog, User user) throws WebloggerEx } catch (NoResultException ignored) { throw new WebloggerException("ERROR: permission not found"); } + // only an invitation can be declined; members leave by resigning + if (!existingPerm.isPending()) { + throw new WebloggerException("ERROR: permission is not a pending invitation"); + } // remove permission this.strategy.remove(existingPerm); } @@ -563,6 +573,94 @@ public List getWeblogPermissions(Weblog weblog) throws Weblogg return q.getResultList(); } + @Override + public boolean updateWeblogMembership(Weblog weblog, Map> changes) + throws WebloggerException { + + List perms; + try { + // every change has to be for a member of, or a user invited to, + // the weblog; check before taking the lock, so a request for + // someone else's weblog doesn't wait for or hold it + checkMemberships(readMemberships(weblog.getHandle()), changes); + + // lock the weblog's row so membership updates for it run one at + // a time + EntityManager em = strategy.getEntityManager(true); + Weblog locked = em.find(Weblog.class, weblog.getId(), LockModeType.PESSIMISTIC_WRITE); + if (locked == null) { + throw new WebloggerException("ERROR: weblog not found"); + } + + // read the memberships again now that the lock is held + perms = readMemberships(locked.getHandle()); + checkMemberships(perms, changes); + } catch (PersistenceException e) { + throw new WebloggerException(e); + } + + boolean adminBefore = false; + boolean adminAfter = false; + for (WeblogPermission perm : perms) { + if (perm.isPending()) { + continue; + } + // a disabled user can't manage the weblog + if (perm.getUser() == null || !Boolean.TRUE.equals(perm.getUser().getEnabled())) { + continue; + } + boolean admin = perm.hasAction(WeblogPermission.ADMIN); + adminBefore |= admin; + if (changes.containsKey(perm.getUserName())) { + List actions = changes.get(perm.getUserName()); + admin = actions != null && actions.contains(WeblogPermission.ADMIN); + } + adminAfter |= admin; + } + if (adminBefore && !adminAfter) { + return false; + } + + for (WeblogPermission perm : perms) { + if (!changes.containsKey(perm.getUserName())) { + continue; + } + // change the row that was read, which also works for a disabled + // user and leaves an invitation pending + List actions = changes.get(perm.getUserName()); + if (actions == null) { + this.strategy.remove(perm); + } else { + perm.setActionsAsList(actions); + this.strategy.store(perm); + } + } + return true; + } + + // a weblog's memberships and invitations, read from the database rather + // than the cache + private List readMemberships(String handle) throws WebloggerException { + TypedQuery q = strategy.getNamedQuery("WeblogPermission.getByWeblogIdIncludingPending", + WeblogPermission.class); + q.setParameter(1, handle); + q.setHint("eclipselink.refresh", "true"); + return q.getResultList(); + } + + private static void checkMemberships(List perms, Map> changes) + throws WebloggerException { + for (String userName : changes.keySet()) { + boolean found = false; + for (WeblogPermission perm : perms) { + found |= perm.getUserName().equals(userName); + } + if (!found) { + throw new WebloggerException("ERROR: permission not found"); + } + } + } + @Override public List getWeblogPermissionsIncludingPending(Weblog weblog) throws WebloggerException { TypedQuery q = strategy.getNamedQuery("WeblogPermission.getByWeblogIdIncludingPending", diff --git a/app/src/main/java/org/apache/roller/weblogger/business/jpa/JPAWeblogManagerImpl.java b/app/src/main/java/org/apache/roller/weblogger/business/jpa/JPAWeblogManagerImpl.java index 60eee749e7..0548cb544b 100644 --- a/app/src/main/java/org/apache/roller/weblogger/business/jpa/JPAWeblogManagerImpl.java +++ b/app/src/main/java/org/apache/roller/weblogger/business/jpa/JPAWeblogManagerImpl.java @@ -202,9 +202,11 @@ private void removeWeblogContents(Weblog weblog) removeCategories.setParameter(1, weblog); removeCategories.executeUpdate(); - // remove permissions - for (WeblogPermission perm : umgr.getWeblogPermissions(weblog)) { - umgr.revokeWeblogPermission(perm.getWeblog(), perm.getUser(), WeblogPermission.ALL_ACTIONS); + // remove permissions, and pending invitations, which a new weblog with + // the same handle would otherwise inherit. The rows are removed + // directly, as a disabled user's can't be looked up through the user. + for (WeblogPermission perm : umgr.getWeblogPermissionsIncludingPending(weblog)) { + this.strategy.remove(perm); } // flush the changes before returning. This is required as there is a diff --git a/app/src/main/java/org/apache/roller/weblogger/business/search/lucene/SearchOperation.java b/app/src/main/java/org/apache/roller/weblogger/business/search/lucene/SearchOperation.java index 47cfb84572..1b85faac1f 100644 --- a/app/src/main/java/org/apache/roller/weblogger/business/search/lucene/SearchOperation.java +++ b/app/src/main/java/org/apache/roller/weblogger/business/search/lucene/SearchOperation.java @@ -40,6 +40,7 @@ import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopFieldCollectorManager; import org.apache.lucene.search.TopFieldDocs; +import org.apache.lucene.util.automaton.TooComplexToDeterminizeException; import org.apache.roller.weblogger.business.search.IndexManager; import org.apache.roller.weblogger.config.WebloggerConfig; @@ -171,6 +172,15 @@ public void doRun() { } catch (ParseException e) { // who cares? parseError = e.getMessage(); + + } catch (IllegalArgumentException | IndexSearcher.TooManyClauses + | TooComplexToDeterminizeException e) { + // Lucene rejects some queries that parse, such as an unfinished + // regular expression or a negative phrase slop, only when it + // builds or runs them. Treat them like a query that does not parse. + logger.debug("Could not run search query: " + e.getMessage()); + searchresults = null; + parseError = e.getMessage() != null ? e.getMessage() : e.getClass().getName(); } // don't need to close the reader, since we didn't do any writing! } diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/LdapCommentAuthenticator.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/LdapCommentAuthenticator.java index fc9737db5d..36a978ddcf 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/LdapCommentAuthenticator.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/LdapCommentAuthenticator.java @@ -25,6 +25,7 @@ import javax.naming.NamingException; import javax.naming.ldap.InitialLdapContext; import javax.naming.ldap.LdapContext; +import javax.naming.ldap.Rdn; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; @@ -153,7 +154,7 @@ public boolean authenticate(HttpServletRequest request) { * @param ldapUser * @return */ - private String getQualifedDc(String ldapDc, String ldapOu, String ldapUser) { + String getQualifedDc(String ldapDc, String ldapOu, String ldapUser) { String qualifedDc = ""; for (String token : StringUtils.delimitedListToStringArray(ldapDc, ",")) { if (!qualifedDc.isEmpty()) { @@ -162,7 +163,9 @@ private String getQualifedDc(String ldapDc, String ldapOu, String ldapUser) { qualifedDc += "dc=" + token; } - return "uid=" + ldapUser + ", ou=" + ldapOu + "," + qualifedDc; + // escape the user name so it stays the uid value and cannot add or + // change other parts of the bind name + return "uid=" + Rdn.escapeValue(ldapUser) + ", ou=" + ldapOu + "," + qualifedDc; } /** diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogFeedRequest.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogFeedRequest.java index 8d1763f334..c0e532dd7d 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogFeedRequest.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogFeedRequest.java @@ -145,7 +145,7 @@ public WeblogFeedRequest(HttpServletRequest request) this.page = parsePageNum(request.getParameter("page")); if(request.getParameter("q") != null && !request.getParameter("q").isBlank()) { - this.term = URLUtilities.decode(request.getParameter("q")); + this.term = WeblogSearchRequest.capQuery(URLUtilities.decode(request.getParameter("q"))); } if(this.tags != null && !this.tags.isEmpty() && this.weblogCategoryName != null) { diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogSearchRequest.java b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogSearchRequest.java index 76a378e170..832c003ebb 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogSearchRequest.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/rendering/util/WeblogSearchRequest.java @@ -37,6 +37,9 @@ public class WeblogSearchRequest extends WeblogRequest { private static Log log = LogFactory.getLog(WeblogSearchRequest.class); public static final String SEARCH_SERVLET = "/roller-ui/rendering/search"; + + /** Longest search query kept, plenty for a person to type. */ + public static final int MAX_QUERY_LENGTH = 256; // lightweight attributes private String query = null; @@ -83,7 +86,7 @@ public WeblogSearchRequest(HttpServletRequest request) * cat - limit results to a certain weblogCategoryName */ if(request.getParameter("q") != null && !request.getParameter("q").isBlank()) { - this.query = request.getParameter("q"); + this.query = capQuery(request.getParameter("q")); } this.pageNum = parsePageNum(request.getParameter("page")); @@ -94,6 +97,48 @@ public WeblogSearchRequest(HttpServletRequest request) } } + /** + * Keeps the first MAX_QUERY_LENGTH characters of a search query, so one + * request cannot hand the query parser unbounded work, such as thousands + * of nested parentheses. Leading and trailing whitespace doesn't count. + * Does not split a surrogate pair, and drops the opening quote of a + * phrase, or an escape character, that the cap cuts off. + */ + public static String capQuery(String query) { + if (query == null) { + return null; + } + query = query.strip(); + if (query.length() <= MAX_QUERY_LENGTH) { + return query; + } + int end = MAX_QUERY_LENGTH; + if (Character.isHighSurrogate(query.charAt(end - 1))) { + end--; + } + String capped = query.substring(0, end); + // find a quote whose phrase the cap cut off; an escaped quote doesn't + // start or end a phrase + int openQuote = -1; + for (int i = 0; i < capped.length(); i++) { + char c = capped.charAt(i); + if (c == '\\') { + if (i == capped.length() - 1) { + // the cap cut off the escaped character + capped = capped.substring(0, i); + } + i++; + } else if (c == '"') { + openQuote = openQuote < 0 ? i : -1; + } + } + // drop it, so the rest still parses + if (openQuote >= 0) { + capped = capped.substring(0, openQuote) + capped.substring(openQuote + 1); + } + return capped; + } + public String getQuery() { return query; } diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/MainMenu.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/MainMenu.java index 58475c6920..8039da48eb 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/MainMenu.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/MainMenu.java @@ -90,6 +90,12 @@ public String decline() { WeblogManager wmgr = WebloggerFactory.getWeblogger().getWeblogManager(); Weblog weblog = wmgr.getWeblog(getInviteId()); String handle = weblog.getHandle(); + // a page loaded before the invitation was accepted still offers + // to decline it + if (umgr.getWeblogPermission(weblog, getAuthenticatedUser()) != null) { + addError("yourWebsites.declineMember", handle); + return DONE; + } // TODO ROLLER_2.0: notify inviter that invitee has declined invitation // TODO EXCEPTIONS: better exception handling here umgr.declineWeblogPermission(weblog, getAuthenticatedUser()); 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..198397a748 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 @@ -69,6 +69,11 @@ public String execute() { } public String save() { + // The federated identity (issuer#subject) decides which account an + // OIDC login opens, so only the OIDC login code sets it. Use the stored + // value, whatever the request carries, for the checks below. + getBean().setOpenIdUrl(getAuthenticatedUser().getOpenIdUrl()); + myValidate(); if (!hasActionErrors()) { @@ -79,20 +84,6 @@ public String save() { // copy updated attributes getBean().copyTo(existingUser); - if (StringUtils.isNotEmpty(getBean().getOpenIdUrl())) { - try { - String openidurl = getBean().getOpenIdUrl(); - if (openidurl != null && openidurl.endsWith("/")) { - openidurl = openidurl.substring(0, openidurl.length() - 1); - } - existingUser.setOpenIdUrl(openidurl); - } catch (Exception ex) { - log.error("Unexpected error saving user OpenID URL", ex); - addError("generic.error.check.logs"); - return INPUT; - } - } - if (authMethod == AuthMethod.DB_OIDC) { if (StringUtils.isEmpty(existingUser.getPassword()) && StringUtils.isEmpty(bean.getPasswordText()) @@ -139,11 +130,11 @@ public void myValidate() { if (RollerPasswordEncoders.isExternalLoginMarker(getBean().getPasswordText())) { addError("error.add.user.reservedPassword"); } + // check that passwords match if they were specified (w/StringUtils.equals, null == null) + if (!StringUtils.equals(getBean().getPasswordText(), getBean().getPasswordConfirm())) { + addError("userRegister.error.mismatchedPasswords"); + } if (StringUtils.isEmpty(getBean().getOpenIdUrl())) { - // check that passwords match if they were specified (w/StringUtils.equals, null == null) - if (!StringUtils.equals(getBean().getPasswordText(), getBean().getPasswordConfirm())) { - addError("userRegister.error.mismatchedPasswords"); - } if (authMethod == AuthMethod.OIDC) { addError("userRegister.error.missingOpenID"); } @@ -152,7 +143,7 @@ public void myValidate() { try { UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); User user = mgr.getUserByOpenIdUrl(bean.getOpenIdUrl()); - if (user != null && !(user.getUserName().equals(bean.getUserName()))) { + if (user != null && !user.getUserName().equals(getAuthenticatedUser().getUserName())) { addError("error.add.user.openIdInUse"); } } catch (WebloggerException ex) { diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/ProfileBean.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/ProfileBean.java index 6e4d721ba9..aa755894f9 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/ProfileBean.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/ProfileBean.java @@ -148,13 +148,13 @@ public void setPasswordConfirm(String passwordConfirm) { public void copyTo(User dataHolder) { - // avoiding password, that is handled separately in class Profile + // avoiding password, that is handled separately in class Profile, and + // the federated identity, which only the OIDC login code sets dataHolder.setScreenName(this.screenName); dataHolder.setFullName(this.fullName); dataHolder.setEmailAddress(this.emailAddress); dataHolder.setLocale(this.locale); dataHolder.setTimeZone(this.timeZone); - dataHolder.setOpenIdUrl(this.openIdUrl); } 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..c6969b908c 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 @@ -194,6 +194,11 @@ public String save() { return DISABLED_RETURN_CODE; } + // The federated identity (issuer#subject) decides which account an + // OIDC login opens, so only the OIDC login code sets it, never the + // registration form. + getBean().setOpenIdUrl(null); + myValidate(); if (!hasActionErrors()) { @@ -246,14 +251,6 @@ public String save() { ud.setActivationCode(inActivationCode); } - String openidurl = getBean().getOpenIdUrl(); - if (openidurl != null) { - if (openidurl.endsWith("/")) { - openidurl = openidurl.substring(0, openidurl.length() - 1); - } - ud.setOpenIdUrl(openidurl); - } - // save new user mgr.addUser(ud); WebloggerFactory.getWeblogger().getPropertiesManager().saveProperty( diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/MemberResign.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/MemberResign.java index 0a1e2e2e08..e80d51cec9 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/MemberResign.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/MemberResign.java @@ -49,11 +49,6 @@ public List requiredWeblogPermissionActions() { return Collections.singletonList(WeblogPermission.EDIT_DRAFT); } - @Override - public boolean isWeblogRequired() { - return false; - } - /** * Show member resign confirmation */ @@ -70,7 +65,13 @@ public String resign() { UserManager umgr = WebloggerFactory.getWeblogger().getUserManager(); // TODO: notify website members that user has resigned // TODO EXCEPTIONS: better exception handling - umgr.revokeWeblogPermission(getActionWeblog(), getAuthenticatedUser(), WeblogPermission.ALL_ACTIONS); + // the check and the removal run as one operation, so concurrent + // membership changes can't leave the weblog without an admin + if (!umgr.updateWeblogMembership(getActionWeblog(), + Collections.singletonMap(getAuthenticatedUser().getUserName(), null))) { + addError("yourWebsites.resign.lastAdmin", getWeblog()); + return SUCCESS; + } WebloggerFactory.getWeblogger().flush(); addMessage("yourWebsites.resigned", getWeblog()); } catch (WebloggerException ex) { diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/Members.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/Members.java index 9f692687b3..5e293f4f1d 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/Members.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/Members.java @@ -20,7 +20,9 @@ package org.apache.roller.weblogger.ui.struts2.editor; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.roller.weblogger.WebloggerException; @@ -101,12 +103,14 @@ public String save() { User user = getAuthenticatedUser(); boolean error = false; for (WeblogPermission perms : permsList) { - String sval = getParameter("perm-" + perms.getUser().getId()); + // each row is keyed by its permission, so a disabled member's + // row can be changed too + String sval = getParameter("perm-" + perms.getId()); if (sval != null) { if (sval.equals(WeblogPermission.ADMIN) && !perms.isPending()) { numAdmins++; } - if (perms.getUser().getUserName().equals(user.getUserName())) { + if (perms.getUserName().equals(user.getUserName())) { // can't modify self if (!sval.equals(WeblogPermission.ADMIN)) { error = true; @@ -120,34 +124,42 @@ public String save() { error = true; } // one iteration for each line (user) in the members table + Map> changes = new LinkedHashMap<>(); for (WeblogPermission perms : permsList) { - String sval = getParameter("perm-" + perms.getUser().getId()); + String sval = getParameter("perm-" + perms.getId()); if (sval != null) { if (!error && !perms.hasAction(sval)) { if ("-1".equals(sval)) { - userMgr.revokeWeblogPermission( - perms.getWeblog(), perms.getUser(), WeblogPermission.ALL_ACTIONS); + changes.put(perms.getUserName(), null); removed++; } else { - userMgr.revokeWeblogPermission( - perms.getWeblog(), perms.getUser(), WeblogPermission.ALL_ACTIONS); - userMgr.grantWeblogPermission( - perms.getWeblog(), perms.getUser(), Utilities.stringToStringList(sval, ",")); + changes.put(perms.getUserName(), Utilities.stringToStringList(sval, ",")); changed++; } } } } - - if (removed > 0 || changed > 0) { - log.debug("Weblog permissions updated, flushing changes"); - WebloggerFactory.getWeblogger().flush(); + + // the admin check is repeated with the changes, as one operation, + // so concurrent membership changes can't leave no admin + if (!changes.isEmpty()) { + if (userMgr.updateWeblogMembership(getActionWeblog(), changes)) { + log.debug("Weblog permissions updated, flushing changes"); + WebloggerFactory.getWeblogger().flush(); + } else { + addError("memberPermissions.oneAdminRequired"); + removed = 0; + changed = 0; + } } - + } catch (Exception ex) { log.error("Error saving permissions on weblog - "+getActionWeblog().getHandle(), ex); addError("memberPermissions.saveError"); + // nothing was saved + removed = 0; + changed = 0; } if (removed > 0) { diff --git a/app/src/main/resources/ApplicationResources.properties b/app/src/main/resources/ApplicationResources.properties index deb045f0c0..490da38f1f 100644 --- a/app/src/main/resources/ApplicationResources.properties +++ b/app/src/main/resources/ApplicationResources.properties @@ -1884,7 +1884,11 @@ decline: yourWebsites.youAreInvited=You are invited to join weblog [{0}] - yourWebsites.declined=You have declined an invitation to join weblog [{0}] +yourWebsites.declineMember=You are already a member of weblog [{0}]. To leave it, resign \ +from it. yourWebsites.resigned=You have resigned from weblog [{0}] +yourWebsites.resign.lastAdmin=You cannot resign from weblog [{0}] because you are its \ +only admin. Make another member an admin first. yourWebsites.permNotFound=Sorry, that invitation was just revoked. yourWebsites.userCount=Members diff --git a/app/src/main/resources/struts.xml b/app/src/main/resources/struts.xml index b809b62ac2..b42df8c646 100644 --- a/app/src/main/resources/struts.xml +++ b/app/src/main/resources/struts.xml @@ -597,12 +597,17 @@ + + + + AUTOMATIC + .MemberResign - + menu /roller-ui - + menu /roller-ui diff --git a/app/src/main/webapp/WEB-INF/jsps/core/Profile.jsp b/app/src/main/webapp/WEB-INF/jsps/core/Profile.jsp index 6f5f117102..98fdeea4bc 100644 --- a/app/src/main/webapp/WEB-INF/jsps/core/Profile.jsp +++ b/app/src/main/webapp/WEB-INF/jsps/core/Profile.jsp @@ -67,7 +67,6 @@ <%-- assigned by the identity provider at login, so shown read-only --%> - diff --git a/app/src/main/webapp/WEB-INF/jsps/editor/Members.jsp b/app/src/main/webapp/WEB-INF/jsps/editor/Members.jsp index 256fb23ac8..a0bf4b689c 100644 --- a/app/src/main/webapp/WEB-INF/jsps/editor/Members.jsp +++ b/app/src/main/webapp/WEB-INF/jsps/editor/Members.jsp @@ -82,26 +82,26 @@ function save() { - + checked - name="perm-" value="admin" /> + name="perm-" value="admin" /> checked - name="perm-" value="post" /> + name="perm-" value="post" /> checked - name="perm-" value="edit_draft" /> + name="perm-" value="edit_draft" /> " value="-1" /> + name="perm-" value="-1" /> diff --git a/app/src/test/java/org/apache/roller/weblogger/business/PermissionTest.java b/app/src/test/java/org/apache/roller/weblogger/business/PermissionTest.java index eb4235c6e5..46881a0458 100644 --- a/app/src/test/java/org/apache/roller/weblogger/business/PermissionTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/business/PermissionTest.java @@ -320,4 +320,113 @@ public void testPermissionChecks() throws Exception { TestUtils.endSession(true); log.info("END"); } + + /** + * Removing a weblog removes its pending invitations, so a weblog later + * created with the same handle doesn't inherit them. + */ + @Test + public void testRemovingWeblogRemovesInvitations() throws Exception { + UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); + User invitee = TestUtils.setupUser("permsInvitee"); + Weblog weblog = TestUtils.setupWeblog("permsInviteWeblog", testUser); + String handle = weblog.getHandle(); + TestUtils.endSession(true); + + mgr.grantWeblogPermissionPending(weblog, invitee, List.of(WeblogPermission.POST)); + TestUtils.endSession(true); + + TestUtils.teardownWeblog(weblog.getId()); + TestUtils.endSession(true); + + Weblog again = TestUtils.setupWeblog("permsInviteWeblog", testUser); + TestUtils.endSession(true); + try { + assertEquals(handle, again.getHandle()); + assertTrue(mgr.getPendingWeblogPermissions(again).isEmpty(), + "the new weblog has no invitations"); + } finally { + TestUtils.teardownWeblog(again.getId()); + TestUtils.teardownUser(invitee.getUserName()); + TestUtils.endSession(true); + } + } + + /** + * Removing a user removes their pending invitations, so a user later + * created with the same name doesn't inherit them. + */ + @Test + public void testRemovingUserRemovesInvitations() throws Exception { + UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); + User invitee = TestUtils.setupUser("permsRemovedInvitee"); + String userName = invitee.getUserName(); + TestUtils.endSession(true); + + mgr.grantWeblogPermissionPending(TestUtils.getManagedWebsite(testWeblog), invitee, + List.of(WeblogPermission.POST)); + TestUtils.endSession(true); + + TestUtils.teardownUser(userName); + TestUtils.endSession(true); + + User again = TestUtils.setupUser("permsRemovedInvitee"); + TestUtils.endSession(true); + try { + assertTrue(mgr.getPendingWeblogPermissions(again).isEmpty(), + "the new user has no invitations"); + } finally { + TestUtils.teardownUser(userName); + TestUtils.endSession(true); + } + } + + /** + * A weblog can be removed when one of its members, or a user invited to + * it, has since been disabled. + */ + @Test + public void testRemovingWeblogWithDisabledMembers() throws Exception { + UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); + User invitee = TestUtils.setupUser("permsDisabledInvitee"); + User member = TestUtils.setupUser("permsDisabledMember"); + Weblog weblog = TestUtils.setupWeblog("permsDisabledWeblog", testUser); + TestUtils.endSession(true); + + mgr.grantWeblogPermissionPending(weblog, invitee, List.of(WeblogPermission.POST)); + mgr.grantWeblogPermission(weblog, member, List.of(WeblogPermission.POST)); + for (User user : List.of(invitee, member)) { + User stored = mgr.getUserByUserName(user.getUserName(), null); + stored.setEnabled(Boolean.FALSE); + mgr.saveUser(stored); + } + TestUtils.endSession(true); + + try { + TestUtils.teardownWeblog(weblog.getId()); + TestUtils.endSession(true); + + assertNull(WebloggerFactory.getWeblogger().getWeblogManager().getWeblog(weblog.getId())); + assertTrue(mgr.getWeblogPermissionsIncludingPending(weblog).isEmpty(), + "the removed weblog has no members or invitations"); + } finally { + // start over in case the removal failed part way + TestUtils.endSession(false); + Weblog left = WebloggerFactory.getWeblogger().getWeblogManager().getWeblog(weblog.getId()); + if (left != null) { + for (User user : List.of(invitee, member)) { + User stored = mgr.getUserByUserName(user.getUserName(), null); + // the removal may have got as far as the memberships + if (mgr.getWeblogPermissionIncludingPending(left, stored) != null) { + mgr.revokeWeblogPermission(left, stored, WeblogPermission.ALL_ACTIONS); + } + } + TestUtils.endSession(true); + TestUtils.teardownWeblog(left.getId()); + } + TestUtils.teardownUser(invitee.getUserName()); + TestUtils.teardownUser(member.getUserName()); + TestUtils.endSession(true); + } + } } diff --git a/app/src/test/java/org/apache/roller/weblogger/business/search/lucene/SearchMalformedQueryTest.java b/app/src/test/java/org/apache/roller/weblogger/business/search/lucene/SearchMalformedQueryTest.java new file mode 100644 index 0000000000..cd0ab5cb91 --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/business/search/lucene/SearchMalformedQueryTest.java @@ -0,0 +1,103 @@ +/* + * 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.business.search.lucene; + +import java.util.concurrent.locks.ReentrantReadWriteLock; + +import org.apache.lucene.analysis.standard.StandardAnalyzer; +import org.apache.lucene.document.Document; +import org.apache.lucene.document.Field; +import org.apache.lucene.document.SortedDocValuesField; +import org.apache.lucene.document.StringField; +import org.apache.lucene.document.TextField; +import org.apache.lucene.index.DirectoryReader; +import org.apache.lucene.index.IndexWriter; +import org.apache.lucene.index.IndexWriterConfig; +import org.apache.lucene.store.ByteBuffersDirectory; +import org.apache.lucene.store.Directory; +import org.apache.lucene.util.BytesRef; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * A query Lucene cannot run finds nothing, the same as a query it cannot + * parse, instead of failing the search. + */ +class SearchMalformedQueryTest { + + @Test + void unfinishedRegularExpressionFindsNothing() throws Exception { + assertFindsNothing("/[/"); + } + + @Test + void negativePhraseSlopFindsNothing() throws Exception { + assertFindsNothing("\"roller entry\"~-5"); + } + + @Test + void unparseableQueryStillFindsNothing() throws Exception { + assertFindsNothing("[a TO"); + } + + @Test + void ordinaryQueryStillFindsTheEntry() throws Exception { + try (Directory dir = index(); DirectoryReader reader = DirectoryReader.open(dir)) { + SearchOperation search = search(reader, "roller"); + search.doRun(); + assertEquals(1, search.getResultsCount()); + } + } + + private static void assertFindsNothing(String query) throws Exception { + try (Directory dir = index(); DirectoryReader reader = DirectoryReader.open(dir)) { + SearchOperation search = search(reader, query); + assertDoesNotThrow(search::doRun, query); + assertEquals(-1, search.getResultsCount(), query); + assertNotNull(search.getParseError(), query); + } + } + + private static Directory index() throws Exception { + Directory dir = new ByteBuffersDirectory(); + try (IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(new StandardAnalyzer()))) { + Document doc = new Document(); + doc.add(new StringField(FieldConstants.ID, "id1", Field.Store.YES)); + doc.add(new TextField(FieldConstants.CONTENT, "roller entry", Field.Store.NO)); + doc.add(new SortedDocValuesField(FieldConstants.PUBLISHED, + new BytesRef("2020-01-01 00:00:00.0"))); + writer.addDocument(doc); + } + return dir; + } + + private static SearchOperation search(DirectoryReader reader, String query) { + LuceneIndexManager manager = mock(LuceneIndexManager.class); + when(manager.getSharedIndexReader()).thenReturn(reader); + when(manager.getReadWriteLock()).thenReturn(new ReentrantReadWriteLock()); + SearchOperation search = new SearchOperation(manager); + search.setTerm(query); + return search; + } +} diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/LdapCommentAuthenticatorTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/LdapCommentAuthenticatorTest.java index 8c1e6a0020..4117a18f7b 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/LdapCommentAuthenticatorTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/plugins/comments/LdapCommentAuthenticatorTest.java @@ -17,11 +17,14 @@ package org.apache.roller.weblogger.ui.rendering.plugins.comments; import java.util.Locale; +import javax.naming.ldap.LdapName; +import javax.naming.ldap.Rdn; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; @@ -70,6 +73,30 @@ void preservesLiteralEntityText() { assertFields(renderReturningVisit(""", """), "&quot;"); } + @Test + void userNameStaysOneValueOfTheBindName() throws Exception { + LdapCommentAuthenticator authenticator = new LdapCommentAuthenticator(); + String[] names = { + "reader", "reader,ou=admins", "reader+cn=admin", "a=b", "back\\slash", + "\"quoted\"", "#hash", " leading", "trailing ", "semi;colon", "", + }; + for (String name : names) { + String dn = authenticator.getQualifedDc("example,com", "people", name); + LdapName parsed = new LdapName(dn); + assertEquals(4, parsed.size(), () -> "bind name for [" + name + "]: " + dn); + Rdn uid = parsed.getRdn(parsed.size() - 1); + assertEquals("uid", uid.getType(), dn); + assertEquals(name, uid.getValue(), dn); + assertEquals("ou=people", parsed.getRdn(parsed.size() - 2).toString(), dn); + } + } + + @Test + void ordinaryUserNameIsUnchanged() { + assertEquals("uid=reader, ou=people,dc=example,dc=com", + new LdapCommentAuthenticator().getQualifedDc("example,com", "people", "reader")); + } + private String renderReturningVisit(String user, String password) { HttpServletRequest request = mock(HttpServletRequest.class); HttpSession session = mock(HttpSession.class); diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/util/SearchQueryLengthTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/util/SearchQueryLengthTest.java new file mode 100644 index 0000000000..443fed4000 --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/util/SearchQueryLengthTest.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.rendering.util; + +import jakarta.servlet.http.HttpServletRequest; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Search requests keep at most the first 256 characters of a query, which is + * plenty for a person and keeps one request from asking the query parser for + * unbounded work, such as thousands of nested parentheses. + */ +class SearchQueryLengthTest { + + private static final String DEEP = "(".repeat(10_000) + "roller"; + + @Test + void searchPageQueryIsCapped() throws Exception { + HttpServletRequest request = request(WeblogSearchRequest.SEARCH_SERVLET, "/team", DEEP); + String query = new WeblogSearchRequest(request).getQuery(); + assertEquals(256, query.length()); + assertEquals(DEEP.substring(0, 256), query); + } + + @Test + void searchFeedQueryIsCapped() throws Exception { + HttpServletRequest request = request("/roller-ui/rendering/feed", "/team/entries/atom", DEEP); + assertEquals(256, new WeblogFeedRequest(request).getTerm().length()); + } + + @Test + void shortQueryIsKept() throws Exception { + HttpServletRequest request = request(WeblogSearchRequest.SEARCH_SERVLET, "/team", "roller weblog"); + assertEquals("roller weblog", new WeblogSearchRequest(request).getQuery()); + } + + @Test + void capDoesNotSplitACharacter() throws Exception { + // a character outside the Basic Multilingual Plane straddling the cap + String query = "a".repeat(255) + "😀" + "tail"; + HttpServletRequest request = request(WeblogSearchRequest.SEARCH_SERVLET, "/team", query); + assertEquals("a".repeat(255), new WeblogSearchRequest(request).getQuery()); + } + + @Test + void capDropsAQuoteItLeavesUnbalanced() throws Exception { + // the cap falls inside the quoted phrase + String query = "x".repeat(250) + " \"roller weblog\""; + HttpServletRequest request = request(WeblogSearchRequest.SEARCH_SERVLET, "/team", query); + assertEquals("x".repeat(250) + " roll", new WeblogSearchRequest(request).getQuery()); + } + + @Test + void capKeepsBalancedQuotes() throws Exception { + String query = "\"roller weblog\" " + "x".repeat(300); + HttpServletRequest request = request(WeblogSearchRequest.SEARCH_SERVLET, "/team", query); + assertEquals(query.substring(0, 256), new WeblogSearchRequest(request).getQuery()); + } + + @Test + void capIgnoresAnEscapedQuote() throws Exception { + // the escaped quote is part of a term, so the phrase after it is the + // one the cap cuts off + String query = "\\\"x " + "x".repeat(240) + " \"roller weblog\""; + HttpServletRequest request = request(WeblogSearchRequest.SEARCH_SERVLET, "/team", query); + String capped = new WeblogSearchRequest(request).getQuery(); + assertEquals("\\\"x " + "x".repeat(240) + " roller web", capped); + } + + @Test + void capDropsAnEscapeCharacterItCutsOff() throws Exception { + String query = "x".repeat(255) + "\\:tail"; + HttpServletRequest request = request(WeblogSearchRequest.SEARCH_SERVLET, "/team", query); + assertEquals("x".repeat(255), new WeblogSearchRequest(request).getQuery()); + } + + @Test + void capIgnoresLeadingWhitespace() throws Exception { + String query = " ".repeat(300) + "roller"; + HttpServletRequest request = request(WeblogSearchRequest.SEARCH_SERVLET, "/team", query); + assertEquals("roller", new WeblogSearchRequest(request).getQuery()); + } + + private static HttpServletRequest request(String servlet, String pathInfo, String query) { + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getServletPath()).thenReturn(servlet); + when(request.getPathInfo()).thenReturn(pathInfo); + when(request.getRequestURL()).thenReturn(new StringBuffer("http://localhost" + servlet + pathInfo)); + when(request.getParameter("q")).thenReturn(query); + return request; + } +} diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/FederatedIdentityFormTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/FederatedIdentityFormTest.java new file mode 100644 index 0000000000..9b1366b063 --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/FederatedIdentityFormTest.java @@ -0,0 +1,274 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.roller.weblogger.ui.struts2.core; + +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpSession; +import org.apache.roller.weblogger.TestUtils; +import org.apache.roller.weblogger.business.UserManager; +import org.apache.roller.weblogger.business.WebloggerFactory; +import org.apache.roller.weblogger.config.WebloggerConfig; +import org.apache.roller.weblogger.config.WebloggerRuntimeConfig; +import org.apache.roller.weblogger.pojos.User; +import org.apache.roller.weblogger.ui.core.RollerContext; +import org.apache.roller.weblogger.ui.core.security.BootstrapSecurity; +import org.apache.roller.weblogger.ui.struts2.util.UIAction; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.springframework.security.crypto.password.PasswordEncoder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +/** + * The federated identity (issuer#subject) stored in User.openIdUrl decides + * which account an OIDC login opens, so only Roller's OIDC login code sets it. + * The profile and registration forms keep whatever is stored, whatever the + * request carries. + */ +class FederatedIdentityFormTest { + + private static final String IDENTITY = "https://idp.example.com#subject-1"; + + private final Map savedProperties = new HashMap<>(); + private String userName; + private PasswordEncoder savedEncoder; + + @BeforeEach + void setUp() throws Exception { + TestUtils.setupWeblogger(); + // RollerContext sets up its password encoder only when the webapp + // starts, so encode passwords with a cheap stand-in. + savedEncoder = swapEncoder(new PasswordEncoder() { + @Override + public String encode(CharSequence raw) { + return "{test}" + Integer.toHexString(raw.toString().hashCode()); + } + + @Override + public boolean matches(CharSequence raw, String encoded) { + return encode(raw).equals(encoded); + } + }); + userName = TestUtils.setupUser("federatedform").getUserName(); + TestUtils.endSession(true); + } + + @AfterEach + void tearDown() throws Exception { + try { + TestUtils.teardownUser(userName); + User registered = WebloggerFactory.getWeblogger().getUserManager() + .getUserByUserName("junitregistered", null); + if (registered != null) { + TestUtils.teardownUser(registered.getUserName()); + } + TestUtils.endSession(true); + } finally { + swapEncoder(savedEncoder); + Properties config = config(); + savedProperties.forEach((k, v) -> { + if (v == null) { + config.remove(k); + } else { + config.setProperty(k, v); + } + }); + } + } + + @Test + void profileSaveDoesNotSetTheIdentity() throws Exception { + Profile profile = profile(); + profile.getBean().setOpenIdUrl(IDENTITY); + + assertEquals(UIAction.SUCCESS, profile.save(), () -> profile.getActionErrors().toString()); + TestUtils.endSession(true); + + assertNull(storedIdentity(userName)); + } + + @Test + void profileSaveDoesNotChangeTheIdentity() throws Exception { + setStoredIdentity(IDENTITY); + Profile profile = profile(); + profile.getBean().setOpenIdUrl("https://other.example.com#subject-2"); + + assertEquals(UIAction.SUCCESS, profile.save(), () -> profile.getActionErrors().toString()); + TestUtils.endSession(true); + + assertEquals(IDENTITY, storedIdentity(userName)); + } + + @Test + void oidcUserSavesProfileWithoutPostingTheIdentity() throws Exception { + setProperty("authentication.method", "oidc"); + setStoredIdentity(IDENTITY); + Profile profile = profile(); + profile.getBean().setOpenIdUrl(null); + profile.getBean().setFullName("Renamed"); + + assertEquals(UIAction.SUCCESS, profile.save(), () -> profile.getActionErrors().toString()); + TestUtils.endSession(true); + + assertEquals(IDENTITY, storedIdentity(userName)); + assertEquals("Renamed", user(userName).getFullName()); + } + + @Test + void dbOidcUserSavesProfileWithoutPostingTheIdentity() throws Exception { + setProperty("authentication.method", "db-oidc"); + setStoredIdentity(IDENTITY); + Profile profile = profile(); + profile.getBean().setOpenIdUrl(null); + + assertEquals(UIAction.SUCCESS, profile.save(), () -> profile.getActionErrors().toString()); + TestUtils.endSession(true); + + assertEquals(IDENTITY, storedIdentity(userName)); + } + + @Test + void mismatchedPasswordsAreRejectedForAUserWithAStoredIdentity() throws Exception { + setStoredIdentity(IDENTITY); + String password = user(userName).getPassword(); + Profile profile = profile(); + profile.getBean().setPasswordText("new-password"); + profile.getBean().setPasswordConfirm("another-password"); + + assertEquals(UIAction.INPUT, profile.save()); + TestUtils.endSession(false); + + assertEquals(password, user(userName).getPassword()); + } + + @Test + void registrationDoesNotSetTheIdentity() throws Exception { + boolean completed = setBootstrapCompleted(true); + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getSession()).thenReturn(mock(HttpSession.class)); + try (MockedStatic runtime = + mockStatic(WebloggerRuntimeConfig.class, CALLS_REAL_METHODS)) { + runtime.when(() -> WebloggerRuntimeConfig.getBooleanProperty("users.registration.enabled")) + .thenReturn(true); + runtime.when(() -> WebloggerRuntimeConfig.getBooleanProperty("user.account.email.activation")) + .thenReturn(false); + + Register register = spy(new Register()); + stubText(register); + register.withServletRequest(request); + ProfileBean bean = register.getBean(); + bean.setUserName("junitregistered"); + bean.setScreenName("registered"); + bean.setFullName("Registered User"); + bean.setEmailAddress("registered@dev.null"); + bean.setLocale("en_US"); + bean.setTimeZone("America/Denver"); + bean.setPasswordText("registered-password"); + bean.setPasswordConfirm("registered-password"); + bean.setOpenIdUrl(IDENTITY); + + assertEquals(UIAction.SUCCESS, register.save(), () -> register.getActionErrors().toString()); + TestUtils.endSession(true); + } finally { + setBootstrapCompleted(completed); + } + + User registered = user("junitregistered"); + assertNotNull(registered); + assertNull(registered.getOpenIdUrl()); + } + + private Profile profile() throws Exception { + Profile profile = spy(new Profile()); + stubText(profile); + User self = user(userName); + ProfileBean bean = new ProfileBean(); + bean.copyFrom(self); + profile.setBean(bean); + profile.setAuthenticatedUser(self); + return profile; + } + + private void setStoredIdentity(String identity) throws Exception { + UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); + User user = mgr.getUserByUserName(userName, null); + user.setOpenIdUrl(identity); + mgr.saveUser(user); + TestUtils.endSession(true); + } + + private static String storedIdentity(String name) throws Exception { + return user(name).getOpenIdUrl(); + } + + private static User user(String name) throws Exception { + return WebloggerFactory.getWeblogger().getUserManager().getUserByUserName(name, null); + } + + private static void stubText(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 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; + } + + private static boolean setBootstrapCompleted(boolean value) throws Exception { + Field field = BootstrapSecurity.class.getDeclaredField("completed"); + field.setAccessible(true); + boolean previous = field.getBoolean(null); + field.setBoolean(null, value); + return previous; + } + + private void setProperty(String key, String value) throws ReflectiveOperationException { + Properties config = config(); + savedProperties.putIfAbsent(key, config.getProperty(key)); + config.setProperty(key, value); + } + + private static Properties config() throws ReflectiveOperationException { + Field field = WebloggerConfig.class.getDeclaredField("config"); + field.setAccessible(true); + return (Properties) field.get(null); + } +} diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/editor/MemberResignResultTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/editor/MemberResignResultTest.java new file mode 100644 index 0000000000..451043c3e5 --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/editor/MemberResignResultTest.java @@ -0,0 +1,220 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. The ASF licenses this file to You + * under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. For additional information regarding + * copyright in this work, please see the NOTICE file in the top level + * directory of this distribution. + */ + +package org.apache.roller.weblogger.ui.struts2.editor; + +import java.security.Principal; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import jakarta.servlet.ServletContext; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; + +import org.apache.roller.weblogger.TestUtils; +import org.apache.roller.weblogger.business.UserManager; +import org.apache.roller.weblogger.business.WebloggerFactory; +import org.apache.roller.weblogger.pojos.User; +import org.apache.roller.weblogger.pojos.Weblog; +import org.apache.roller.weblogger.pojos.WeblogPermission; +import org.apache.roller.weblogger.ui.struts2.util.UIAction; +import org.apache.struts2.ActionProxy; +import org.apache.struts2.ActionProxyFactory; +import org.apache.struts2.dispatcher.Dispatcher; +import org.apache.struts2.dispatcher.mapper.ActionMapping; +import org.apache.struts2.interceptor.MessageStoreInterceptor; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Resigning from a weblog goes back to the main menu, which shows whether + * the resignation worked. Runs the action through Struts, so the configured + * results and interceptors are used. + */ +class MemberResignResultTest { + + private Dispatcher dispatcher; + private String ownerName; + private String memberName; + private String weblogId; + private String handle; + + @BeforeEach + void setUp() throws Exception { + TestUtils.setupWeblogger(); + User owner = TestUtils.setupUser("resignresultowner"); + User member = TestUtils.setupUser("resignresultmember"); + ownerName = owner.getUserName(); + memberName = member.getUserName(); + // the creator becomes the weblog's administrator + Weblog weblog = TestUtils.setupWeblog("resignresulttest", owner); + weblogId = weblog.getId(); + handle = weblog.getHandle(); + TestUtils.endSession(true); + + // building action objects through Spring needs a running webapp; the + // results and interceptors don't depend on which factory creates + // actions + dispatcher = new Dispatcher(mock(ServletContext.class), + Collections.singletonMap("struts.objectFactory", "struts")); + dispatcher.init(); + Dispatcher.setInstance(dispatcher); + } + + @AfterEach + void tearDown() throws Exception { + try { + dispatcher.cleanup(); + Dispatcher.setInstance(null); + } finally { + TestUtils.endSession(true); + TestUtils.teardownWeblog(weblogId); + TestUtils.teardownUser(ownerName); + TestUtils.teardownUser(memberName); + TestUtils.endSession(true); + } + } + + @Test + void lastAdministratorIsToldWhyTheyCannotResign() throws Exception { + Map session = new HashMap<>(); + HttpServletResponse response = resign(ownerName, session); + + assertRedirectedToMainMenu(response); + Collection errors = (Collection) session.get(MessageStoreInterceptor.actionErrorsSessionKey); + assertNotNull(errors, "the error is kept for the main menu"); + assertEquals(1, errors.size()); + assertTrue(errors.iterator().next().toString().contains(handle), errors::toString); + TestUtils.endSession(true); + assertNotNull(permission(ownerName), "the weblog keeps its last administrator"); + } + + @Test + void memberIsToldThatTheyResigned() throws Exception { + users().grantWeblogPermission(weblog(), user(memberName), List.of(WeblogPermission.POST)); + TestUtils.endSession(true); + + Map session = new HashMap<>(); + HttpServletResponse response = resign(memberName, session); + + assertRedirectedToMainMenu(response); + Collection messages = (Collection) session.get(MessageStoreInterceptor.actionMessagesSessionKey); + assertNotNull(messages, "the message is kept for the main menu"); + assertEquals(1, messages.size()); + TestUtils.endSession(true); + assertNull(permission(memberName)); + } + + @Test + void resigningFromAWeblogThatDoesNotExistIsDenied() throws Exception { + // the access-denied page is a Tiles result, which needs a running + // webapp, so only the action's result code is checked + assertEquals(UIAction.DENIED, invoke(ownerName, "resignresultnosuchweblog", new HashMap<>(), + mock(HttpServletResponse.class), false)); + TestUtils.endSession(true); + assertNotNull(permission(ownerName)); + } + + @Test + void aUserWhoIsNotAMemberCannotResign() throws Exception { + assertEquals(UIAction.DENIED, invoke(memberName, handle, new HashMap<>(), + mock(HttpServletResponse.class), false)); + } + + private static void assertRedirectedToMainMenu(HttpServletResponse response) throws Exception { + ArgumentCaptor location = ArgumentCaptor.forClass(String.class); + verify(response).sendRedirect(location.capture()); + assertTrue(location.getValue().startsWith("/roller-ui/menu"), location.getValue()); + } + + // posts the resignation form for the weblog as the named user, keeping + // the HTTP session's attributes in the given map + private HttpServletResponse resign(String name, Map sessionAttributes) throws Exception { + HttpServletResponse response = mock(HttpServletResponse.class); + when(response.encodeRedirectURL(anyString())).thenAnswer(call -> call.getArgument(0)); + invoke(name, handle, sessionAttributes, response, true); + return response; + } + + // posts the resignation form for the given weblog handle and returns the + // action's result code + private String invoke(String name, String weblogHandle, Map sessionAttributes, + HttpServletResponse response, boolean executeResult) throws Exception { + HttpSession session = mock(HttpSession.class); + when(session.getId()).thenReturn("resign-session"); + when(session.getAttribute(anyString())).thenAnswer(call -> sessionAttributes.get(call.getArgument(0))); + doAnswer(call -> sessionAttributes.put(call.getArgument(0), call.getArgument(1))) + .when(session).setAttribute(anyString(), any()); + + Map requestAttributes = new HashMap<>(); + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getMethod()).thenReturn("POST"); + when(request.getSession()).thenReturn(session); + when(request.getSession(false)).thenReturn(session); + when(request.getSession(true)).thenReturn(session); + Principal principal = () -> name; + when(request.getUserPrincipal()).thenReturn(principal); + when(request.getParameterMap()).thenReturn(Map.of("weblog", new String[] {weblogHandle})); + when(request.getParameter("weblog")).thenReturn(weblogHandle); + when(request.getLocale()).thenReturn(Locale.ENGLISH); + when(request.getAttribute(anyString())).thenAnswer(call -> requestAttributes.get(call.getArgument(0))); + doAnswer(call -> requestAttributes.put(call.getArgument(0), call.getArgument(1))) + .when(request).setAttribute(anyString(), any()); + when(request.getServletPath()).thenReturn("/roller-ui/authoring/memberResign!resign.rol"); + when(request.getContextPath()).thenReturn(""); + + ActionMapping mapping = new ActionMapping("memberResign", "/roller-ui/authoring", "resign", new HashMap<>()); + Map context = dispatcher.createContextMap(request, response, mapping); + ActionProxy proxy = dispatcher.getContainer().getInstance(ActionProxyFactory.class) + .createActionProxy("/roller-ui/authoring", "memberResign", "resign", context, executeResult, false); + return proxy.execute(); + } + + private WeblogPermission permission(String name) throws Exception { + return users().getWeblogPermissionIncludingPending(weblog(), user(name)); + } + + private static UserManager users() { + return WebloggerFactory.getWeblogger().getUserManager(); + } + + private Weblog weblog() throws Exception { + return WebloggerFactory.getWeblogger().getWeblogManager().getWeblog(weblogId); + } + + private static User user(String name) throws Exception { + return users().getUserByUserName(name, null); + } +} diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/editor/WeblogMembershipTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/editor/WeblogMembershipTest.java new file mode 100644 index 0000000000..a9f9a69d1d --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/editor/WeblogMembershipTest.java @@ -0,0 +1,516 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.roller.weblogger.ui.struts2.editor; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import org.apache.roller.weblogger.TestUtils; +import org.apache.roller.weblogger.WebloggerException; +import org.apache.roller.weblogger.business.UserManager; +import org.apache.roller.weblogger.business.WebloggerFactory; +import org.apache.roller.weblogger.pojos.User; +import org.apache.roller.weblogger.pojos.Weblog; +import org.apache.roller.weblogger.pojos.WeblogPermission; +import org.apache.roller.weblogger.ui.struts2.core.MainMenu; +import org.apache.roller.weblogger.ui.struts2.util.UIAction; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.spy; + +/** + * Declining an invitation removes only a pending invitation, and a weblog's + * last administrator cannot resign from it. + */ +class WeblogMembershipTest { + + private String ownerName; + private String memberName; + private String weblogId; + private String handle; + + @BeforeEach + void setUp() throws Exception { + TestUtils.setupWeblogger(); + User owner = TestUtils.setupUser("membershipowner"); + User member = TestUtils.setupUser("membershipmember"); + ownerName = owner.getUserName(); + memberName = member.getUserName(); + // the creator becomes the weblog's administrator + Weblog weblog = TestUtils.setupWeblog("membershiptest", owner); + weblogId = weblog.getId(); + handle = weblog.getHandle(); + TestUtils.endSession(true); + } + + @AfterEach + void tearDown() throws Exception { + // removing the weblog also removes its memberships and invitations + TestUtils.teardownWeblog(weblogId); + TestUtils.teardownUser(ownerName); + TestUtils.teardownUser(memberName); + TestUtils.endSession(true); + } + + @Test + void decliningAPendingInvitationRemovesIt() throws Exception { + users().grantWeblogPermissionPending(weblog(), user(memberName), + List.of(WeblogPermission.POST)); + TestUtils.endSession(true); + + decline(memberName); + + assertNull(permission(memberName)); + } + + @Test + void decliningKeepsAnAcceptedMembership() throws Exception { + users().grantWeblogPermission(weblog(), user(memberName), List.of(WeblogPermission.POST)); + TestUtils.endSession(true); + + MainMenu menu = decline(memberName); + + assertNotNull(permission(memberName), "an accepted membership is not an invitation"); + assertEquals(List.of("yourWebsites.declineMember"), new ArrayList<>(menu.getActionErrors())); + } + + @Test + void soleAdministratorCannotDeclineTheirOwnMembership() throws Exception { + decline(ownerName); + + assertNotNull(permission(ownerName)); + } + + @Test + void lastAdministratorCannotResign() throws Exception { + MemberResign action = resign(ownerName); + + assertTrue(action.hasActionErrors()); + assertNotNull(permission(ownerName), "the weblog keeps its last administrator"); + } + + @Test + void pendingAdministratorDoesNotCountAsAnotherAdministrator() throws Exception { + users().grantWeblogPermissionPending(weblog(), user(memberName), + List.of(WeblogPermission.ADMIN)); + TestUtils.endSession(true); + + MemberResign action = resign(ownerName); + + assertTrue(action.hasActionErrors()); + assertNotNull(permission(ownerName)); + } + + @Test + void disabledAdministratorDoesNotCountAsAnotherAdministrator() throws Exception { + users().grantWeblogPermission(weblog(), user(memberName), List.of(WeblogPermission.ADMIN)); + User member = user(memberName); + member.setEnabled(Boolean.FALSE); + users().saveUser(member); + TestUtils.endSession(true); + + MemberResign action = resign(ownerName); + + assertTrue(action.hasActionErrors()); + assertNotNull(permission(ownerName), "a disabled administrator can't manage the weblog"); + } + + @Test + void administratorCanResignWhenAnotherRemains() throws Exception { + users().grantWeblogPermission(weblog(), user(memberName), List.of(WeblogPermission.ADMIN)); + TestUtils.endSession(true); + + MemberResign action = resign(ownerName); + + assertFalse(action.hasActionErrors()); + assertNull(permission(ownerName)); + } + + @Test + void memberCanResign() throws Exception { + users().grantWeblogPermission(weblog(), user(memberName), List.of(WeblogPermission.POST)); + TestUtils.endSession(true); + + MemberResign action = resign(memberName); + + assertFalse(action.hasActionErrors()); + assertNull(permission(memberName)); + assertNotNull(permission(ownerName)); + } + + @Test + void membershipUpdateRefusesToRemoveTheLastAdministrator() throws Exception { + users().grantWeblogPermission(weblog(), user(memberName), List.of(WeblogPermission.POST)); + TestUtils.endSession(true); + + assertFalse(users().updateWeblogMembership(weblog(), + Collections.singletonMap(ownerName, null))); + TestUtils.endSession(true); + assertNotNull(permission(ownerName)); + + assertFalse(users().updateWeblogMembership(weblog(), + Map.of(ownerName, List.of(WeblogPermission.POST))), "downgrading the last administrator"); + TestUtils.endSession(true); + assertTrue(permission(ownerName).hasAction(WeblogPermission.ADMIN)); + } + + @Test + void membershipUpdateAppliesChangesThatKeepAnAdministrator() throws Exception { + users().grantWeblogPermission(weblog(), user(memberName), List.of(WeblogPermission.POST)); + TestUtils.endSession(true); + + // promote the member and remove the owner in one update + Map> changes = new java.util.HashMap<>(); + changes.put(memberName, List.of(WeblogPermission.ADMIN)); + changes.put(ownerName, null); + assertTrue(users().updateWeblogMembership(weblog(), changes)); + TestUtils.endSession(true); + + assertNull(permission(ownerName)); + assertTrue(permission(memberName).hasAction(WeblogPermission.ADMIN)); + } + + @Test + void membersPageChangesMembershipThroughTheSharedUpdate() throws Exception { + users().grantWeblogPermission(weblog(), user(memberName), List.of(WeblogPermission.POST)); + TestUtils.endSession(true); + + Members action = spy(new Members()); + stubText(action); + action.setAuthenticatedUser(user(ownerName)); + action.setActionWeblog(weblog()); + doAnswer(call -> null).when(action).getParameter(anyString()); + doAnswer(call -> WeblogPermission.ADMIN).when(action).getParameter("perm-" + permission(ownerName).getId()); + doAnswer(call -> WeblogPermission.ADMIN).when(action).getParameter("perm-" + permission(memberName).getId()); + action.save(); + TestUtils.endSession(true); + + assertFalse(action.hasActionErrors()); + assertTrue(permission(memberName).hasAction(WeblogPermission.ADMIN)); + assertTrue(permission(ownerName).hasAction(WeblogPermission.ADMIN)); + } + + @Test + void disabledMemberCanBeRemoved() throws Exception { + users().grantWeblogPermission(weblog(), user(memberName), List.of(WeblogPermission.POST)); + disable(memberName); + + assertTrue(users().updateWeblogMembership(weblog(), + Collections.singletonMap(memberName, null))); + TestUtils.endSession(true); + + assertNull(permission(memberName)); + } + + @Test + void disabledMemberCanBeDemoted() throws Exception { + users().grantWeblogPermission(weblog(), user(memberName), List.of(WeblogPermission.POST)); + disable(memberName); + + assertTrue(users().updateWeblogMembership(weblog(), + Map.of(memberName, List.of(WeblogPermission.EDIT_DRAFT)))); + TestUtils.endSession(true); + + assertEquals(List.of(WeblogPermission.EDIT_DRAFT), permission(memberName).getActionsAsList()); + } + + @Test + void changingAPendingInvitationKeepsItPending() throws Exception { + users().grantWeblogPermissionPending(weblog(), user(memberName), + List.of(WeblogPermission.POST)); + TestUtils.endSession(true); + + assertTrue(users().updateWeblogMembership(weblog(), + Map.of(memberName, List.of(WeblogPermission.ADMIN)))); + TestUtils.endSession(true); + + WeblogPermission invitation = permission(memberName); + assertEquals(List.of(WeblogPermission.ADMIN), invitation.getActionsAsList()); + assertTrue(invitation.isPending(), "the invitation has not been accepted"); + } + + @Test + void nonMemberCannotResign() throws Exception { + MemberResign action = resign(memberName); + + assertTrue(action.hasActionErrors()); + assertFalse(action.hasActionMessages(), "nobody resigned"); + } + + @Test + void membershipUpdateRejectsAUserWithoutAMembership() throws Exception { + Map> changes = new java.util.HashMap<>(); + changes.put(ownerName, List.of(WeblogPermission.POST)); + changes.put(memberName, List.of(WeblogPermission.ADMIN)); + + assertThrows(WebloggerException.class, + () -> users().updateWeblogMembership(weblog(), changes)); + TestUtils.endSession(false); + + assertTrue(permission(ownerName).hasAction(WeblogPermission.ADMIN), "nothing was changed"); + assertNull(permission(memberName)); + } + + @Test + void membershipUpdateForANonMemberDoesNotWaitForAnotherUpdate() throws Exception { + CountDownLatch updating = new CountDownLatch(1); + CountDownLatch finish = new CountDownLatch(1); + ExecutorService pool = Executors.newFixedThreadPool(2); + try { + // an update that has started and not yet finished + Future update = pool.submit(() -> { + try { + users().updateWeblogMembership(weblog(), + Map.of(ownerName, List.of(WeblogPermission.ADMIN))); + updating.countDown(); + return finish.await(60, TimeUnit.SECONDS); + } finally { + WebloggerFactory.getWeblogger().release(); + } + }); + assertTrue(updating.await(30, TimeUnit.SECONDS)); + + Future refused = pool.submit(() -> { + try { + return assertThrows(WebloggerException.class, () -> users().updateWeblogMembership( + weblog(), Collections.singletonMap(memberName, null))); + } finally { + WebloggerFactory.getWeblogger().release(); + } + }); + refused.get(10, TimeUnit.SECONDS); + finish.countDown(); + update.get(30, TimeUnit.SECONDS); + } finally { + finish.countDown(); + pool.shutdownNow(); + } + } + + @Test + void membersPageReportsNoChangesWhenSavingFails() throws Exception { + users().grantWeblogPermission(weblog(), user(memberName), List.of(WeblogPermission.POST)); + TestUtils.endSession(true); + // a weblog whose memberships can be read but not changed + Weblog unsaved = new Weblog(); + unsaved.setId("membershiptest-unsaved"); + unsaved.setHandle(handle); + + Members action = spy(new Members()); + stubText(action); + action.setAuthenticatedUser(user(ownerName)); + action.setActionWeblog(unsaved); + doAnswer(call -> null).when(action).getParameter(anyString()); + doAnswer(call -> WeblogPermission.ADMIN).when(action).getParameter("perm-" + permission(ownerName).getId()); + doAnswer(call -> "-1").when(action).getParameter("perm-" + permission(memberName).getId()); + action.save(); + TestUtils.endSession(false); + + assertTrue(action.hasActionErrors()); + assertFalse(action.hasActionMessages(), () -> action.getActionMessages().toString()); + assertNotNull(permission(memberName), "nothing was saved"); + } + + @Test + void membersPageSavesWhenAMemberIsDisabled() throws Exception { + users().grantWeblogPermission(weblog(), user(memberName), List.of(WeblogPermission.POST)); + disable(memberName); + + Members action = spy(new Members()); + stubText(action); + action.setAuthenticatedUser(user(ownerName)); + action.setActionWeblog(weblog()); + doAnswer(call -> null).when(action).getParameter(anyString()); + doAnswer(call -> WeblogPermission.ADMIN).when(action).getParameter("perm-" + permission(ownerName).getId()); + action.save(); + TestUtils.endSession(true); + + assertFalse(action.hasActionErrors(), () -> action.getActionErrors().toString()); + assertTrue(permission(memberName).hasAction(WeblogPermission.POST)); + } + + @Test + void membersPageRemovesADisabledMember() throws Exception { + users().grantWeblogPermission(weblog(), user(memberName), List.of(WeblogPermission.POST)); + disable(memberName); + + Members action = membersSaving(Map.of( + ownerName, WeblogPermission.ADMIN, + memberName, "-1")); + TestUtils.endSession(true); + + assertNull(permission(memberName), "the disabled member was removed"); + assertFalse(action.hasActionErrors(), () -> action.getActionErrors().toString()); + } + + @Test + void membersPageChangesADisabledMembersRole() throws Exception { + users().grantWeblogPermission(weblog(), user(memberName), List.of(WeblogPermission.POST)); + disable(memberName); + + Members action = membersSaving(Map.of( + ownerName, WeblogPermission.ADMIN, + memberName, WeblogPermission.EDIT_DRAFT)); + TestUtils.endSession(true); + + assertEquals(List.of(WeblogPermission.EDIT_DRAFT), permission(memberName).getActionsAsList()); + assertFalse(action.hasActionErrors(), () -> action.getActionErrors().toString()); + } + + @Test + void concurrentResignationsLeaveAnAdministrator() throws Exception { + for (int round = 0; round < 5; round++) { + for (String name : List.of(ownerName, memberName)) { + if (permission(name) != null) { + users().revokeWeblogPermission(weblog(), user(name), WeblogPermission.ALL_ACTIONS); + } + } + TestUtils.endSession(true); + users().grantWeblogPermission(weblog(), user(ownerName), List.of(WeblogPermission.ADMIN)); + users().grantWeblogPermission(weblog(), user(memberName), List.of(WeblogPermission.ADMIN)); + TestUtils.endSession(true); + + CyclicBarrier start = new CyclicBarrier(2); + ExecutorService pool = Executors.newFixedThreadPool(2); + try { + List> results = new ArrayList<>(); + for (String name : List.of(ownerName, memberName)) { + results.add(pool.submit(() -> { + try { + MemberResign action = spy(new MemberResign()); + stubText(action); + action.setAuthenticatedUser(user(name)); + action.setActionWeblog(weblog()); + action.setWeblog(handle); + start.await(10, TimeUnit.SECONDS); + action.resign(); + return !action.hasActionErrors(); + } finally { + WebloggerFactory.getWeblogger().release(); + } + })); + } + int resigned = 0; + for (Future result : results) { + if (result.get(60, TimeUnit.SECONDS)) { + resigned++; + } + } + assertEquals(1, resigned, "only one of the two administrators can resign"); + } finally { + pool.shutdownNow(); + } + TestUtils.endSession(true); + int admins = 0; + for (WeblogPermission perm : users().getWeblogPermissions(weblog())) { + if (perm.hasAction(WeblogPermission.ADMIN)) { + admins++; + } + } + assertEquals(1, admins, "the weblog keeps an administrator"); + } + } + + private MainMenu decline(String name) throws Exception { + MainMenu menu = spy(new MainMenu()); + stubText(menu); + menu.setAuthenticatedUser(user(name)); + menu.setInviteId(weblogId); + menu.decline(); + TestUtils.endSession(true); + return menu; + } + + private MemberResign resign(String name) throws Exception { + MemberResign action = spy(new MemberResign()); + stubText(action); + action.setAuthenticatedUser(user(name)); + action.setActionWeblog(weblog()); + action.setWeblog(handle); + action.resign(); + TestUtils.endSession(true); + return action; + } + + // saves the Members page with a choice for each named member, submitted + // in the field the page renders for that member's permission + private Members membersSaving(Map choices) throws Exception { + Members action = spy(new Members()); + stubText(action); + action.setAuthenticatedUser(user(ownerName)); + action.setActionWeblog(weblog()); + doAnswer(call -> null).when(action).getParameter(anyString()); + for (Map.Entry choice : choices.entrySet()) { + doAnswer(call -> choice.getValue()).when(action) + .getParameter("perm-" + permission(choice.getKey()).getId()); + } + action.save(); + return action; + } + + private static void disable(String name) throws Exception { + User user = user(name); + user.setEnabled(Boolean.FALSE); + users().saveUser(user); + TestUtils.endSession(true); + } + + private WeblogPermission permission(String name) throws Exception { + return users().getWeblogPermissionIncludingPending(weblog(), user(name)); + } + + private static void stubText(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()); + doAnswer(call -> call.getArgument(0)).when(action) + .getText(anyString(), anyString(), anyString()); + } + + private static UserManager users() { + return WebloggerFactory.getWeblogger().getUserManager(); + } + + private Weblog weblog() throws Exception { + return WebloggerFactory.getWeblogger().getWeblogManager().getWeblog(weblogId); + } + + private static User user(String name) throws Exception { + return users().getUserByUserName(name, null); + } +}