diff --git a/CHANGES.md b/CHANGES.md index 549a1ff55c..e91b5f0d37 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -48,8 +48,8 @@ refused with 413 before they're stored, and entries show the creator's email address only to the creator (also in MetaWeblog responses) (#328). -- **Search queries are limited to 256 characters**, and a query the search - engine can't run finds nothing (#334). +- **Search queries are limited to 256 characters**, after spaces around them + are dropped, and a query the search engine can't run finds nothing (#334). - **Weblog pages ignore a `skipCache` query parameter** (#325). @@ -79,8 +79,11 @@ - **"nofollow" is added to links that need it.** `addNofollow` only touched links that already had `rel="nofollow"` (#330). - **Tags of a scheduled entry are counted once, when it goes live** (#328). -- **A weblog's only administrator can't resign from it**, and declining an - invitation only removes a pending invitation (#334). +- **A weblog's only administrator can't resign from it**, and the main menu + says why. Resigning now redirects to the main menu, as accepting and + declining an invitation do. Declining an invitation only removes a pending + invitation, and declining one you already accepted says you're already a + member (#334). - **New passwords can't be the external-login placeholder.** Registration, the profile page and user administration refuse `users.passwords.externalAuthValue` (by default ``) as a 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 266fa1cfa3..c53f61617e 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 @@ -282,6 +282,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 df957ce3a5..0828a9d353 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 @@ -32,7 +32,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; @@ -77,7 +80,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); } @@ -513,6 +519,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); } @@ -562,6 +572,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 b7baeab87e..4903f465f5 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 @@ -220,9 +220,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 04b1305bf2..8d9f93b748 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 @@ -38,6 +38,7 @@ import org.apache.lucene.search.SortField; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopFieldDocs; +import org.apache.lucene.util.automaton.TooComplexToDeterminizeException; import org.apache.roller.weblogger.business.search.IndexManager; /** @@ -150,6 +151,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 b851048ff1..43e969b8db 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 @@ -24,6 +24,7 @@ import javax.naming.NamingException; import javax.naming.ldap.InitialLdapContext; import javax.naming.ldap.LdapContext; +import javax.naming.ldap.Rdn; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; @@ -152,7 +153,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()) { @@ -161,7 +162,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 93e9d96174..06a61b392c 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 @@ -144,7 +144,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 8fb8db1dd1..0aadae5b36 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 @@ -36,6 +36,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; @@ -82,7 +85,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")); @@ -93,6 +96,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 37164317f6..51686660ea 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 @@ -88,6 +88,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/editor/MemberResign.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/MemberResign.java index 3d7c997486..b2b6364995 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 @@ -65,11 +65,21 @@ public String execute() { * Resign from a weblog */ public String resign() { + // isWeblogRequired() is false, so the weblog may not exist + if (getActionWeblog() == null) { + return DENIED; + } try { 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 bda8961946..358b99e8c5 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 @@ -19,6 +19,7 @@ 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; @@ -93,12 +94,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; @@ -112,34 +115,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 690a8746bc..a11af7267f 100644 --- a/app/src/main/resources/ApplicationResources.properties +++ b/app/src/main/resources/ApplicationResources.properties @@ -1875,7 +1875,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 f1f984da03..b074bcfd69 100644 --- a/app/src/main/resources/struts.xml +++ b/app/src/main/resources/struts.xml @@ -638,12 +638,17 @@ + + + + AUTOMATIC + .MemberResign - + menu /roller-ui - + menu /roller-ui 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 dff79b33c0..491de2735c 100644 --- a/app/src/main/webapp/WEB-INF/jsps/editor/Members.jsp +++ b/app/src/main/webapp/WEB-INF/jsps/editor/Members.jsp @@ -81,26 +81,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 d9672cff21..91194bb1d7 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 @@ -319,4 +319,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 08e25cfc19..09fffe5a82 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 javax.servlet.http.HttpServletRequest; import javax.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..52acc6c30e --- /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 javax.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/editor/MemberResignResultTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/editor/MemberResignResultTest.java new file mode 100644 index 0000000000..da96994f9b --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/editor/MemberResignResultTest.java @@ -0,0 +1,204 @@ +/* + * 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 javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import com.opensymphony.xwork2.ActionProxy; +import com.opensymphony.xwork2.ActionProxyFactory; +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.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() { + // no weblog of the requested handle + assertEquals(UIAction.DENIED, new MemberResign().resign()); + } + + 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 { + 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[] {handle})); + when(request.getParameter("weblog")).thenReturn(handle); + 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(""); + + HttpServletResponse response = mock(HttpServletResponse.class); + when(response.encodeRedirectURL(anyString())).thenAnswer(call -> call.getArgument(0)); + + 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, true, false); + proxy.execute(); + return response; + } + + 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); + } +}