This is an automated email from the ASF dual-hosted git repository.
snoopdave pushed a commit to branch roller-6.1.x
in repository https://gitbox.apache.org/repos/asf/roller.git
The following commit(s) were added to refs/heads/roller-6.1.x by this push:
new 0303a525b Protect weblog admins, escape the LDAP comment user name,
and limit search queries (#334)
0303a525b is described below
commit 0303a525b1f40ff38073c4d73a163b307fd43ea0
Author: Matt Raible <[email protected]>
AuthorDate: Sat Nov 21 11:32:10 2026 -0700
Protect weblog admins, escape the LDAP comment user name, and limit search
queries (#334)
* Decline only pending invitations and keep a weblog's last admin from
resigning
Declining a weblog invitation now removes the permission only while it is
still pending, so it can no longer remove an accepted membership. Resigning
from a weblog is refused, with a message, when the user is the weblog's only
admin; pending invitations do not count as another admin.
* Escape the commenter's user name in the LDAP comment authenticator's bind
name
LdapCommentAuthenticator now escapes the submitted user name with
Rdn.escapeValue before putting it in the uid part of the bind DN, so characters
such as commas, plus signs and equals signs stay part of the user name.
* Limit search query length and treat queries Lucene cannot run as finding
nothing
WeblogSearchRequest and WeblogFeedRequest now keep only the first 256
characters of the q parameter, without splitting a surrogate pair.
SearchOperation now catches runtime exceptions that Lucene throws for queries
that parse but cannot be built or run, such as an unfinished regular expression
or a negative phrase slop. It logs them as a warning and handles them the same
way as a query that does not parse.
* Check for a remaining weblog admin and change memberships in one locked
operation
Resigning from a weblog and saving the Members page now go through
UserManager.updateWeblogMembership(), which locks the weblog's row, reads its
memberships again, and applies the changes in the same transaction only if an
enabled administrator remains. Concurrent membership changes for a weblog
therefore run one after the other and can't leave it without an administrator,
and a disabled user who holds ADMIN no longer counts as one.
* Remove pending invitations along with their weblog or user
Removing a weblog or a user now also removes its pending invitations, so a
weblog or user created later with the same name doesn't inherit them.
* Handle disabled members and non-members in weblog membership changes
Removing a weblog now deletes its permission rows directly, so a member or
invited user who has since been disabled no longer stops the removal with a
NullPointerException.
updateWeblogMembership changes the permission rows it read under the lock
instead of revoking and granting through the user, which works for disabled
members. A pending invitation whose role changes still stays pending, and a
test now covers that. It also fails with "permission not found" when a change
names a user who has no membership or invitation, so resigning from a weblog
you don't belong to reports an error again rather than success.
The Members page skips rows for disabled members when saving, since the
form has no field that can address them, instead of failing every save on that
weblog.
* Key Members page rows by permission so disabled members can be changed
The Members page named each row's radio buttons after the member's user id,
which it got through WeblogPermission.getUser(). That lookup only finds enabled
users, so a disabled member's row rendered with a blank name and a field the
save could not match, and an admin could not remove the member or change their
role.
Each row is now keyed by its permission id and shows the user name stored
on the permission, so save() no longer needs to look up the user. New page
tests remove a disabled member and change a disabled member's role.
* Drop the opening quote of a phrase that the search query limit cuts off
When the 256-character limit ends inside a quoted phrase, the search and
feed requests now drop that phrase's opening quote, so the rest of the query
still parses and finds entries instead of nothing.
* Check that a membership change is for a member before locking the weblog
updateWeblogMembership() now checks that every change is for a member of,
or a user invited to, the weblog before it takes the weblog's row lock, and
checks again once the lock is held. A request to resign from a weblog the user
doesn't belong to now fails straight away instead of waiting for, and then
holding, the lock.
A database error while taking the lock or reading the memberships is
reported as a WebloggerException, so the Members and Resign pages show their
usual error message.
* Show no change counts on the Members page when saving fails
Members.save() counted the removals and changes while building the update,
so a failed save showed "Removed 1 user(s)" next to "Error saving permissions".
The counts are now cleared when the save fails.
* Show the outcome of resigning from a weblog on the main menu
Resigning chained to the main menu. When resigning was refused because the
user is the weblog's only admin, the error carried over to the main menu, which
has no input page, so the user got a "No result defined" error page instead of
the message. Resigning now redirects to the main menu and keeps its messages
across the redirect, as accepting and declining an invitation do. The redirect
also ends the request as soon as the change is made or refused.
Resigning with a weblog handle that doesn't exist now shows the access
denied page instead of failing with an error.
* Cap search queries without counting escaped quotes or surrounding
whitespace
The search query limit now skips an escaped quote when it looks for a
phrase that the limit cuts off, and drops an escape character whose escaped
character is cut off, so the capped query still parses. Leading and trailing
whitespace is stripped before the limit is applied, so a query padded with
spaces keeps its search terms.
* Treat only query errors from Lucene as a search that finds nothing
The search operation caught every runtime exception as a query Lucene
couldn't run and logged it as a one-line warning. It now catches only the
exceptions Lucene throws for such queries and logs them at debug level, like a
query that doesn't parse. Other failures, such as an index that can't be
opened, are logged as errors with their stack trace again.
* Tell a member who declines an accepted invitation that they're already a
member
A main menu page loaded before an invitation was accepted still offers to
decline it. Declining then said that the invitation was just revoked and logged
an error with a stack trace. It now says that the user is already a member of
the weblog and can resign to leave it.
* Tidy the membership test cleanup
The membership tests no longer revoke memberships before removing the
weblog, since removing it now removes its invitations too. The permission
test's cleanup revokes only memberships that are still there, so it can't hide
the original failure.
* Say in CHANGES how resigning, declining and search queries behave now
---
CHANGES.md | 11 +-
.../roller/weblogger/business/UserManager.java | 15 +
.../weblogger/business/jpa/JPAUserManagerImpl.java | 100 +++-
.../business/jpa/JPAWeblogManagerImpl.java | 8 +-
.../business/search/lucene/SearchOperation.java | 10 +
.../plugins/comments/LdapCommentAuthenticator.java | 7 +-
.../ui/rendering/util/WeblogFeedRequest.java | 2 +-
.../ui/rendering/util/WeblogSearchRequest.java | 47 +-
.../roller/weblogger/ui/struts2/core/MainMenu.java | 6 +
.../weblogger/ui/struts2/editor/MemberResign.java | 12 +-
.../weblogger/ui/struts2/editor/Members.java | 39 +-
.../main/resources/ApplicationResources.properties | 4 +
app/src/main/resources/struts.xml | 9 +-
.../main/webapp/WEB-INF/jsps/editor/Members.jsp | 10 +-
.../roller/weblogger/business/PermissionTest.java | 109 +++++
.../search/lucene/SearchMalformedQueryTest.java | 103 ++++
.../comments/LdapCommentAuthenticatorTest.java | 27 ++
.../ui/rendering/util/SearchQueryLengthTest.java | 112 +++++
.../ui/struts2/editor/MemberResignResultTest.java | 204 ++++++++
.../ui/struts2/editor/WeblogMembershipTest.java | 516 +++++++++++++++++++++
20 files changed, 1317 insertions(+), 34 deletions(-)
diff --git a/CHANGES.md b/CHANGES.md
index 8fc7e5782..2dbf9731d 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -53,8 +53,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).
@@ -84,8 +84,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 `<externalAuth>`) 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 266fa1cfa..c53f61617 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 @@ public interface UserManager {
List<WeblogPermission> 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<String, List<String>>
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 df957ce3a..0828a9d35 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.HashMap;
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 class JPAUserManagerImpl implements UserManager {
String userName = user.getUserName();
// remove permissions, maintaining both sides of relationship
- List<WeblogPermission> perms = getWeblogPermissions(user);
+ List<WeblogPermission> 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 class JPAUserManagerImpl implements UserManager {
} 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 class JPAUserManagerImpl implements UserManager {
return q.getResultList();
}
+ @Override
+ public boolean updateWeblogMembership(Weblog weblog, Map<String,
List<String>> changes)
+ throws WebloggerException {
+
+ List<WeblogPermission> 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<String> 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<String> 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<WeblogPermission> readMemberships(String handle) throws
WebloggerException {
+ TypedQuery<WeblogPermission> q =
strategy.getNamedQuery("WeblogPermission.getByWeblogIdIncludingPending",
+ WeblogPermission.class);
+ q.setParameter(1, handle);
+ q.setHint("eclipselink.refresh", "true");
+ return q.getResultList();
+ }
+
+ private static void checkMemberships(List<WeblogPermission> perms,
Map<String, List<String>> 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<WeblogPermission> getWeblogPermissionsIncludingPending(Weblog
weblog) throws WebloggerException {
TypedQuery<WeblogPermission> 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 b7baeab87..4903f465f 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 @@ public class JPAWeblogManagerImpl implements WeblogManager
{
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 04b1305bf..8d9f93b74 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.Sort;
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 class SearchOperation extends
ReadFromIndexOperation {
} 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 b851048ff..43e969b8d 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.Context;
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 class LdapCommentAuthenticator implements
CommentAuthenticator {
* @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 @@ public class LdapCommentAuthenticator implements
CommentAuthenticator {
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 93e9d9617..06a61b392 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 class WeblogFeedRequest extends WeblogRequest {
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 8fb8db1dd..0aadae5b3 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 class WeblogSearchRequest extends WeblogRequest {
* 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 class WeblogSearchRequest extends WeblogRequest {
}
}
+ /**
+ * 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 37164317f..51686660e 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 class MainMenu extends UIAction {
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 3d7c99748..b2b636499 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 class MemberResign extends UIAction {
* 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 bda896194..358b99e8c 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 class Members extends UIAction implements
HttpParametersAware {
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 class Members extends UIAction implements
HttpParametersAware {
error = true;
}
// one iteration for each line (user) in the members table
+ Map<String, List<String>> 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 af58a7e8b..2c5835b4c 100644
--- a/app/src/main/resources/ApplicationResources.properties
+++ b/app/src/main/resources/ApplicationResources.properties
@@ -1877,7 +1877,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 f1f984da0..b074bcfd6 100644
--- a/app/src/main/resources/struts.xml
+++ b/app/src/main/resources/struts.xml
@@ -638,12 +638,17 @@
<action name="memberResign"
class="org.apache.roller.weblogger.ui.struts2.editor.MemberResign">
+ <interceptor-ref name="rollerStack"/>
+ <!-- keep messages across the redirect to the main menu -->
+ <interceptor-ref name="store">
+ <param name="operationMode">AUTOMATIC</param>
+ </interceptor-ref>
<result name="input" type="tiles">.MemberResign</result>
- <result name="error" type="chain">
+ <result name="error" type="redirectAction">
<param name="actionName">menu</param>
<param name="namespace">/roller-ui</param>
</result>
- <result name="success" type="chain">
+ <result name="success" type="redirectAction">
<param name="actionName">menu</param>
<param name="namespace">/roller-ui</param>
</result>
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 dff79b33c..491de2735 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() {
<td class="rollertable">
<span class="glyphicon glyphicon-user"></span>
- <s:property value="#perm.user.userName" />
+ <s:property value="#perm.userName" />
</td>
<td class="rollertable">
<input type="radio"
<s:if test='#perm.hasAction("admin")'>checked</s:if>
- name="perm-<s:property value="#perm.user.id" />"
value="admin" />
+ name="perm-<s:property value="#perm.id" />"
value="admin" />
</td>
<td class="rollertable">
<input type="radio"
<s:if test='#perm.hasAction("post")'>checked</s:if>
- name="perm-<s:property value="#perm.user.id" />"
value="post" />
+ name="perm-<s:property value="#perm.id" />"
value="post" />
</td>
<td class="rollertable">
<input type="radio"
<s:if
test='#perm.hasAction("edit_draft")'>checked</s:if>
- name="perm-<s:property value="#perm.user.id" />"
value="edit_draft" />
+ name="perm-<s:property value="#perm.id" />"
value="edit_draft" />
</td>
<td class="rollertable">
<input type="radio"
- name="perm-<s:property value="#perm.user.id" />"
value="-1" />
+ name="perm-<s:property value="#perm.id" />" value="-1"
/>
</td>
</tr>
</s:iterator>
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 d9672cff2..91194bb1d 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 class PermissionTest {
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 000000000..cd0ab5cb9
--- /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 08e25cfc1..09fffe5a8 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 @@ class LdapCommentAuthenticatorTest {
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",
"<angle>",
+ };
+ 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 000000000..52acc6c30
--- /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 000000000..da96994f9
--- /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<String, Object> 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<String, Object> 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<String> 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<String, Object>
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<String, Object> 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<String, Object> 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 000000000..a9f9a69d1
--- /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<String, List<String>> 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<String, List<String>> 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<Future<Boolean>> 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<Boolean> 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<String, String> 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<String, String> 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);
+ }
+}