You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@james.apache.org by rc...@apache.org on 2026/10/09 04:38:05 UTC

(james-project) branch master updated (6aa73cd655 -> b8eabb3d9a)

This is an automated email from the ASF dual-hosted git repository.

Arsnael pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/james-project.git


    from 6aa73cd655 [BUILD] DeletedMessageVaultIntegrationTest: isolate using different users
     new 455256dc60 [FIX] Allow working with capped LDAP pages: paging for /users
     new b8eabb3d9a [ENHANCEMENT] GET /users: search by username prefix and domain via typed UsernamePredicate

The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .../modules/servers/partials/operate/webadmin.adoc |  22 +++
 .../org/apache/james/user/api/UsersRepository.java |  17 ++
 .../james/user/api/model/UsernamePredicate.java    |  73 ++++++++
 .../user/api/model/UsersPaginationHelpers.java     |  66 +++++++
 .../james/user/ldap/ReadOnlyLDAPUsersDAO.java      | 179 +++++++++++++++----
 .../ldap/ReadOnlyLDAPUsersDAOPaginationTest.java   | 192 +++++++++++++++++++++
 .../user/ldap/ReadOnlyUsersLDAPRepositoryTest.java |  80 +++++++++
 .../java/org/apache/james/user/lib/UsersDAO.java   |  11 ++
 .../apache/james/user/lib/UsersRepositoryImpl.java |   7 +
 .../james/user/lib/UsersRepositoryContract.java    | 148 ++++++++++++++++
 .../apache/james/webadmin/routes/UserRoutes.java   |  47 ++++-
 .../apache/james/webadmin/service/UserService.java |  32 +++-
 .../james/webadmin/routes/UserRoutesTest.java      |   5 +-
 13 files changed, 829 insertions(+), 50 deletions(-)
 create mode 100644 server/data/data-api/src/main/java/org/apache/james/user/api/model/UsernamePredicate.java
 create mode 100644 server/data/data-api/src/main/java/org/apache/james/user/api/model/UsersPaginationHelpers.java
 create mode 100644 server/data/data-ldap/src/test/java/org/apache/james/user/ldap/ReadOnlyLDAPUsersDAOPaginationTest.java


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org


(james-project) 01/02: [FIX] Allow working with capped LDAP pages: paging for /users

Posted by rc...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

Arsnael pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/james-project.git

commit 455256dc602645b62b936e1901fc6542e399ef24
Author: Benoit TELLIER <bt...@linagora.com>
AuthorDate: Wed Oct 7 21:53:07 2026 +0200

    [FIX] Allow working with capped LDAP pages: paging for /users
---
 .../modules/servers/partials/operate/webadmin.adoc |  20 +++
 .../org/apache/james/user/api/UsersRepository.java |  45 +++++++
 .../james/user/ldap/ReadOnlyLDAPUsersDAO.java      | 142 ++++++++++++++++-----
 .../java/org/apache/james/user/lib/UsersDAO.java   |  14 ++
 .../apache/james/user/lib/UsersRepositoryImpl.java |  10 ++
 .../apache/james/webadmin/routes/UserRoutes.java   |  19 ++-
 .../apache/james/webadmin/service/UserService.java |  46 +++++--
 .../james/webadmin/routes/UserRoutesTest.java      |   4 +-
 8 files changed, 251 insertions(+), 49 deletions(-)

diff --git a/docs/modules/servers/partials/operate/webadmin.adoc b/docs/modules/servers/partials/operate/webadmin.adoc
index a5f11aa393..ad5527450f 100644
--- a/docs/modules/servers/partials/operate/webadmin.adoc
+++ b/docs/modules/servers/partials/operate/webadmin.adoc
@@ -699,6 +699,26 @@ curl -XGET http://ip:port/users?hasNoMailboxes
 curl -XGET http://ip:port/users?hasNotAllSystemMailboxes
 ....
 
+- `limit`, `anchor` and `query` allow paginating and searching the user list. Users are sorted alphabetically on their
+username.
+  - `limit`: maximum count of users returned (strictly positive integer). No limit if omitted.
+  - `anchor`: only users whose username comes strictly after the anchor are returned. Pass the last username of the
+previous page to get the next one.
+  - `query`: only users whose username contains (case insensitively) this value are returned.
+
+....
+curl -XGET http://ip:port/users?limit=50
+curl -XGET http://ip:port/users?limit=50&anchor=btellier@linagora.com
+curl -XGET http://ip:port/users?query=bte&limit=50&anchor=btellier@linagora.com
+....
+
+These parameters can be combined with the condition parameters above.
+
+Response codes:
+
+* 200: The user name list was successfully retrieved
+* 400: Invalid `limit` or `anchor`
+
 === Retrieving the list of allowed `From` headers for a given user
 
 This endpoint allows to know which From headers a given user is allowed to use when sending mails.
diff --git a/server/data/data-api/src/main/java/org/apache/james/user/api/UsersRepository.java b/server/data/data-api/src/main/java/org/apache/james/user/api/UsersRepository.java
index b730b3e6c3..5ccbd989f5 100644
--- a/server/data/data-api/src/main/java/org/apache/james/user/api/UsersRepository.java
+++ b/server/data/data-api/src/main/java/org/apache/james/user/api/UsersRepository.java
@@ -19,7 +19,9 @@
 
 package org.apache.james.user.api;
 
+import java.util.Comparator;
 import java.util.Iterator;
+import java.util.Locale;
 import java.util.Optional;
 
 import org.apache.james.core.Domain;
@@ -187,6 +189,49 @@ public interface UsersRepository {
             .then();
     }
 
+    Comparator<Username> USERNAME_ALPHABETICAL_ORDER = Comparator.comparing(Username::asString);
+
+    /**
+     * Lists users sorted alphabetically on their username.
+     *
+     * @param anchor exclusive lower bound: only users strictly after it are returned
+     * @param limit maximum count of users returned, no limit if empty
+     */
+    default Publisher<Username> listPaginated(Optional<Username> anchor, Optional<Integer> limit) {
+        return applyLimit(Flux.from(listReactive())
+            .filter(username -> isAfter(username, anchor))
+            .sort(USERNAME_ALPHABETICAL_ORDER), limit);
+    }
+
+    /**
+     * Lists users whose username contains (case insensitively) the query, sorted alphabetically on their username.
+     *
+     * @param query substring the username needs to contain
+     * @param anchor exclusive lower bound: only users strictly after it are returned
+     * @param limit maximum count of users returned, no limit if empty
+     */
+    default Publisher<Username> searchPaginated(String query, Optional<Username> anchor, Optional<Integer> limit) {
+        return applyLimit(Flux.from(listReactive())
+            .filter(username -> matches(username, query))
+            .filter(username -> isAfter(username, anchor))
+            .sort(USERNAME_ALPHABETICAL_ORDER), limit);
+    }
+
+    static Flux<Username> applyLimit(Flux<Username> usernames, Optional<Integer> limit) {
+        return limit.map(value -> usernames.take(value, true))
+            .orElse(usernames);
+    }
+
+    static boolean isAfter(Username username, Optional<Username> anchor) {
+        return anchor.map(a -> USERNAME_ALPHABETICAL_ORDER.compare(username, a) > 0)
+            .orElse(true);
+    }
+
+    static boolean matches(Username username, String query) {
+        return username.asString().toLowerCase(Locale.US)
+            .contains(query.toLowerCase(Locale.US));
+    }
+
     default Publisher<Username> listUsersOfADomainReactive(Domain domain) {
         return Flux.from(listReactive())
             .filter(username -> username.getDomainPart()
diff --git a/server/data/data-ldap/src/main/java/org/apache/james/user/ldap/ReadOnlyLDAPUsersDAO.java b/server/data/data-ldap/src/main/java/org/apache/james/user/ldap/ReadOnlyLDAPUsersDAO.java
index d769fc2fc4..f1e20f054d 100644
--- a/server/data/data-ldap/src/main/java/org/apache/james/user/ldap/ReadOnlyLDAPUsersDAO.java
+++ b/server/data/data-ldap/src/main/java/org/apache/james/user/ldap/ReadOnlyLDAPUsersDAO.java
@@ -26,6 +26,9 @@ import java.util.List;
 import java.util.Map;
 import java.util.Optional;
 import java.util.Set;
+import java.util.TreeSet;
+import java.util.function.Consumer;
+import java.util.function.Predicate;
 import java.util.stream.Stream;
 
 
@@ -39,32 +42,39 @@ import org.apache.james.core.Domain;
 import org.apache.james.core.Username;
 import org.apache.james.lifecycle.api.Configurable;
 import org.apache.james.metrics.api.GaugeRegistry;
+import org.apache.james.user.api.UsersRepository;
 import org.apache.james.user.api.UsersRepositoryException;
 import org.apache.james.user.api.model.User;
 import org.apache.james.user.lib.UsersDAO;
+import org.reactivestreams.Publisher;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import com.github.fge.lambdas.Throwing;
 import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableSet;
+import com.unboundid.asn1.ASN1OctetString;
 import com.unboundid.ldap.sdk.Attribute;
 import com.unboundid.ldap.sdk.DN;
 import com.unboundid.ldap.sdk.Entry;
 import com.unboundid.ldap.sdk.Filter;
+import com.unboundid.ldap.sdk.LDAPConnection;
 import com.unboundid.ldap.sdk.LDAPConnectionPool;
 import com.unboundid.ldap.sdk.LDAPException;
-import com.unboundid.ldap.sdk.LDAPSearchException;
 import com.unboundid.ldap.sdk.SearchRequest;
 import com.unboundid.ldap.sdk.SearchResult;
 import com.unboundid.ldap.sdk.SearchResultEntry;
 import com.unboundid.ldap.sdk.SearchScope;
+import com.unboundid.ldap.sdk.controls.SimplePagedResultsControl;
 
 import reactor.core.publisher.Flux;
+import reactor.core.publisher.Mono;
 import reactor.core.scheduler.Schedulers;
 
 public class ReadOnlyLDAPUsersDAO implements UsersDAO, Configurable {
     private static final Logger LOGGER = LoggerFactory.getLogger(ReadOnlyLDAPUsersDAO.class);
+    private static final int LDAP_PAGE_SIZE = 500;
 
     private final GaugeRegistry gaugeRegistry;
     private final LdapRepositoryConfiguration ldapConfiguration;
@@ -184,35 +194,69 @@ public class ReadOnlyLDAPUsersDAO implements UsersDAO, Configurable {
             ldapConfiguration.getPerDomainBaseDN().values().stream());
     }
 
-    private Stream<SearchResultEntry> entriesFromDN(String dn) throws LDAPSearchException {
+    private Stream<SearchResultEntry> entriesFromDN(String dn) throws LDAPException {
         return entriesFromDN(dn, SearchRequest.NO_ATTRIBUTES);
     }
 
-    private Stream<SearchResultEntry> entriesFromDN(String dn, String attributes) throws LDAPSearchException {
-        SearchRequest searchRequest = new SearchRequest(dn,
-            SearchScope.SUB,
-            listingFilter,
-            attributes);
+    private Stream<SearchResultEntry> entriesFromDN(String dn, String attributes) throws LDAPException {
+        return pagedSearch(dn, listingFilter, attributes).stream();
+    }
 
-        return ldapConnectionPool.search(searchRequest)
-            .getSearchEntries()
-            .stream();
+    private List<SearchResultEntry> pagedSearch(String dn, Filter filter, String attributes) throws LDAPException {
+        ImmutableList.Builder<SearchResultEntry> entries = ImmutableList.builder();
+        pagedSearch(dn, filter, attributes, entries::add);
+        return entries.build();
     }
 
-    private Stream<Username> getAllUsernamesFromLDAP() throws LDAPException {
-        String usernameAttribute = ldapConfiguration.getUsernameAttribute().orElse(ldapConfiguration.getUserIdAttribute());
-        return allDNs()
-            .flatMap(Throwing.<String, Stream<SearchResultEntry>>function(s -> entriesFromDN(s, usernameAttribute)).sneakyThrow())
-            .flatMap(entry -> Optional.ofNullable(entry.getAttribute(usernameAttribute)).stream())
+    /**
+     * Relies on the simple paged results control (RFC 2696) so that listing a large directory is not capped by the
+     * server size limit. The paging cookie is bound to the LDAP connection thus all pages are read on the same connection.
+     */
+    private void pagedSearch(String dn, Filter filter, String attributes, Consumer<SearchResultEntry> entryConsumer) throws LDAPException {
+        LDAPConnection connection = ldapConnectionPool.getConnection();
+        try {
+            ASN1OctetString cookie = null;
+            do {
+                SearchRequest searchRequest = new SearchRequest(dn, SearchScope.SUB, filter, attributes);
+                searchRequest.setControls(new SimplePagedResultsControl(LDAP_PAGE_SIZE, cookie));
+                SearchResult searchResult = connection.search(searchRequest);
+                searchResult.getSearchEntries().forEach(entryConsumer);
+
+                SimplePagedResultsControl responseControl = SimplePagedResultsControl.get(searchResult);
+                cookie = Optional.ofNullable(responseControl)
+                    .filter(SimplePagedResultsControl::moreResultsToReturn)
+                    .map(SimplePagedResultsControl::getCookie)
+                    .orElse(null);
+            } while (cookie != null);
+            ldapConnectionPool.releaseConnection(connection);
+        } catch (LDAPException e) {
+            ldapConnectionPool.releaseConnectionAfterException(connection, e);
+            throw e;
+        }
+    }
+
+    private String usernameAttribute() {
+        return ldapConfiguration.getUsernameAttribute().orElse(ldapConfiguration.getUserIdAttribute());
+    }
+
+    private Optional<Username> asUsername(SearchResultEntry entry, String usernameAttribute) {
+        return Optional.ofNullable(entry.getAttribute(usernameAttribute))
             .map(Attribute::getValue)
             .flatMap(name -> {
                 try {
-                    return Stream.of(Username.of(name));
+                    return Optional.of(Username.of(name));
                 } catch (Exception e) {
                     LOGGER.warn("Invalid username in the LDAP: {}", name, e);
-                    return Stream.empty();
+                    return Optional.empty();
                 }
-            })
+            });
+    }
+
+    private Stream<Username> getAllUsernamesFromLDAP() throws LDAPException {
+        String usernameAttribute = usernameAttribute();
+        return allDNs()
+            .flatMap(Throwing.<String, Stream<SearchResultEntry>>function(s -> entriesFromDN(s, usernameAttribute)).sneakyThrow())
+            .flatMap(entry -> asUsername(entry, usernameAttribute).stream())
             .distinct();
     }
 
@@ -348,6 +392,49 @@ public class ReadOnlyLDAPUsersDAO implements UsersDAO, Configurable {
     }
 
 
+    @Override
+    public Publisher<Username> listPaginated(Optional<Username> anchor, Optional<Integer> limit) {
+        if (ldapConfiguration.getRestriction().isActivated()) {
+            return UsersDAO.super.listPaginated(anchor, limit);
+        }
+        return firstUsernamesAfter(listingFilter, username -> true, anchor, limit);
+    }
+
+    @Override
+    public Publisher<Username> searchPaginated(String query, Optional<Username> anchor, Optional<Integer> limit) {
+        if (ldapConfiguration.getRestriction().isActivated()) {
+            return UsersDAO.super.searchPaginated(query, anchor, limit);
+        }
+        Filter queryFilter = Filter.createSubstringFilter(usernameAttribute(), null, new String[]{query}, null);
+        return firstUsernamesAfter(Filter.createANDFilter(listingFilter, queryFilter),
+            username -> UsersRepository.matches(username, query), anchor, limit);
+    }
+
+    /**
+     * Only the username attribute is retrieved, and only the 'limit' first usernames after the anchor are retained
+     * in memory while the (paged) LDAP search results are being read.
+     */
+    private Flux<Username> firstUsernamesAfter(Filter filter, Predicate<Username> predicate, Optional<Username> anchor, Optional<Integer> limit) {
+        String usernameAttribute = usernameAttribute();
+        return Mono.fromCallable(() -> {
+                TreeSet<Username> firstUsernames = new TreeSet<>(UsersRepository.USERNAME_ALPHABETICAL_ORDER);
+                for (String dn : allDNs().toList()) {
+                    pagedSearch(dn, filter, usernameAttribute, entry -> asUsername(entry, usernameAttribute)
+                        .filter(predicate)
+                        .filter(username -> UsersRepository.isAfter(username, anchor))
+                        .ifPresent(username -> {
+                            firstUsernames.add(username);
+                            if (limit.isPresent() && firstUsernames.size() > limit.get()) {
+                                firstUsernames.pollLast();
+                            }
+                        }));
+                }
+                return firstUsernames;
+            })
+            .flatMapIterable(usernames -> usernames)
+            .subscribeOn(Schedulers.boundedElastic());
+    }
+
     @Override
     public Flux<Username> listUsersOfADomainReactive(Domain domain, boolean supportsVirtualHosting) {
         return Flux.fromStream(() -> {
@@ -371,22 +458,11 @@ public class ReadOnlyLDAPUsersDAO implements UsersDAO, Configurable {
     }
 
     private Stream<Username> getUnrestrictedUsernamesForDomain(Domain domain) throws LDAPException {
-        String usernameAttribute = ldapConfiguration.getUsernameAttribute().orElse(ldapConfiguration.getUserIdAttribute());
+        String usernameAttribute = usernameAttribute();
         Filter domainFilter = Filter.createSubstringFilter(usernameAttribute, null, null, "@" + domain.asString());
-        SearchRequest searchRequest = new SearchRequest(userBase(domain), SearchScope.SUB,
-            Filter.createANDFilter(listingFilter, domainFilter), usernameAttribute);
-        return ldapConnectionPool.search(searchRequest)
-            .getSearchEntries().stream()
-            .flatMap(entry -> Optional.ofNullable(entry.getAttribute(usernameAttribute)).stream())
-            .map(Attribute::getValue)
-            .flatMap(name -> {
-                try {
-                    return Stream.of(Username.of(name));
-                } catch (Exception e) {
-                    LOGGER.warn("Invalid username in the LDAP: {}", name, e);
-                    return Stream.empty();
-                }
-            })
+        return pagedSearch(userBase(domain), Filter.createANDFilter(listingFilter, domainFilter), usernameAttribute)
+            .stream()
+            .flatMap(entry -> asUsername(entry, usernameAttribute).stream())
             .filter(username -> username.getDomainPart().map(domain::equals).orElse(!ldapConfiguration.supportsVirtualHosting()))
             .distinct();
     }
diff --git a/server/data/data-library/src/main/java/org/apache/james/user/lib/UsersDAO.java b/server/data/data-library/src/main/java/org/apache/james/user/lib/UsersDAO.java
index 38b818e5a2..f18b52cf74 100644
--- a/server/data/data-library/src/main/java/org/apache/james/user/lib/UsersDAO.java
+++ b/server/data/data-library/src/main/java/org/apache/james/user/lib/UsersDAO.java
@@ -24,6 +24,7 @@ import java.util.Optional;
 
 import org.apache.james.core.Domain;
 import org.apache.james.core.Username;
+import org.apache.james.user.api.UsersRepository;
 import org.apache.james.user.api.UsersRepositoryException;
 import org.apache.james.user.api.model.User;
 import org.apache.james.util.ReactorUtils;
@@ -72,5 +73,18 @@ public interface UsersDAO {
                 .orElse(!supportsVirtualHosting));
     }
 
+    default Publisher<Username> listPaginated(Optional<Username> anchor, Optional<Integer> limit) {
+        return UsersRepository.applyLimit(Flux.from(listReactive())
+            .filter(username -> UsersRepository.isAfter(username, anchor))
+            .sort(UsersRepository.USERNAME_ALPHABETICAL_ORDER), limit);
+    }
+
+    default Publisher<Username> searchPaginated(String query, Optional<Username> anchor, Optional<Integer> limit) {
+        return UsersRepository.applyLimit(Flux.from(listReactive())
+            .filter(username -> UsersRepository.matches(username, query))
+            .filter(username -> UsersRepository.isAfter(username, anchor))
+            .sort(UsersRepository.USERNAME_ALPHABETICAL_ORDER), limit);
+    }
+
     void addUser(Username username, String password) throws UsersRepositoryException;
 }
diff --git a/server/data/data-library/src/main/java/org/apache/james/user/lib/UsersRepositoryImpl.java b/server/data/data-library/src/main/java/org/apache/james/user/lib/UsersRepositoryImpl.java
index b8cbbdba8c..bc0bcf1780 100644
--- a/server/data/data-library/src/main/java/org/apache/james/user/lib/UsersRepositoryImpl.java
+++ b/server/data/data-library/src/main/java/org/apache/james/user/lib/UsersRepositoryImpl.java
@@ -262,6 +262,16 @@ public class UsersRepositoryImpl<T extends UsersDAO> implements UsersRepository,
         return usersDAO.listReactive();
     }
 
+    @Override
+    public Publisher<Username> listPaginated(Optional<Username> anchor, Optional<Integer> limit) {
+        return usersDAO.listPaginated(anchor, limit);
+    }
+
+    @Override
+    public Publisher<Username> searchPaginated(String query, Optional<Username> anchor, Optional<Integer> limit) {
+        return usersDAO.searchPaginated(query, anchor, limit);
+    }
+
     @Override
     public Publisher<Username> listUsersOfADomainReactive(Domain domain) {
         return usersDAO.listUsersOfADomainReactive(domain, supportVirtualHosting());
diff --git a/server/protocols/webadmin/webadmin-data/src/main/java/org/apache/james/webadmin/routes/UserRoutes.java b/server/protocols/webadmin/webadmin-data/src/main/java/org/apache/james/webadmin/routes/UserRoutes.java
index 8e0ff8faed..b62e4b1b94 100644
--- a/server/protocols/webadmin/webadmin-data/src/main/java/org/apache/james/webadmin/routes/UserRoutes.java
+++ b/server/protocols/webadmin/webadmin-data/src/main/java/org/apache/james/webadmin/routes/UserRoutes.java
@@ -25,6 +25,7 @@ import static spark.Spark.halt;
 
 import java.util.List;
 import java.util.Map;
+import java.util.Optional;
 
 import jakarta.inject.Inject;
 
@@ -50,6 +51,7 @@ import org.apache.james.webadmin.utils.ErrorResponder.ErrorType;
 import org.apache.james.webadmin.utils.JsonExtractException;
 import org.apache.james.webadmin.utils.JsonExtractor;
 import org.apache.james.webadmin.utils.JsonTransformer;
+import org.apache.james.webadmin.utils.ParametersExtractor;
 import org.apache.james.webadmin.utils.Parsers;
 import org.apache.james.webadmin.utils.Responses;
 import org.eclipse.jetty.http.HttpStatus;
@@ -74,6 +76,8 @@ public class UserRoutes implements Routes {
     private static final String FORCE_PARAM = "force";
     private static final String VERIFY = "verify";
     private static final String AUTHORIZED_USERS = "authorizedUsers";
+    private static final String QUERY_PARAM = "query";
+    private static final String ANCHOR_PARAM = "anchor";
 
     private final UserService userService;
     private final JsonTransformer jsonTransformer;
@@ -174,16 +178,21 @@ public class UserRoutes implements Routes {
             jsonTransformer);
     }
 
-    private List<UserResponse> getUsers(Request request, Response response) throws UsersRepositoryException {
+    private List<UserResponse> getUsers(Request request, Response response) {
         UserCondition combinedCondition = userConditionMap.entrySet()
             .stream()
             .filter(entry -> request.queryParams().contains(entry.getKey()))
             .map(Map.Entry::getValue)
             .reduce(ALL, UserCondition::and);
-        return userService.getUsers()
-            .stream()
-            .filter(userResponse -> combinedCondition.test(Username.of(userResponse.getUsername())))
-            .toList();
+
+        Optional<Integer> limit = ParametersExtractor.extractLimit(request).getLimit();
+        Optional<String> query = Optional.ofNullable(request.queryParams(QUERY_PARAM))
+            .filter(s -> !s.isEmpty());
+        Optional<Username> anchor = Optional.ofNullable(request.queryParams(ANCHOR_PARAM))
+            .filter(s -> !s.isEmpty())
+            .map(Parsers::parseUsername);
+
+        return userService.getUsers(query, anchor, limit, combinedCondition);
     }
 
     private String removeUser(Request request, Response response) {
diff --git a/server/protocols/webadmin/webadmin-data/src/main/java/org/apache/james/webadmin/service/UserService.java b/server/protocols/webadmin/webadmin-data/src/main/java/org/apache/james/webadmin/service/UserService.java
index 0de2f37580..5a798728b7 100644
--- a/server/protocols/webadmin/webadmin-data/src/main/java/org/apache/james/webadmin/service/UserService.java
+++ b/server/protocols/webadmin/webadmin-data/src/main/java/org/apache/james/webadmin/service/UserService.java
@@ -19,9 +19,10 @@
 
 package org.apache.james.webadmin.service;
 
+import java.util.ArrayList;
 import java.util.List;
 import java.util.Optional;
-import java.util.stream.Stream;
+import java.util.function.Predicate;
 
 import jakarta.inject.Inject;
 
@@ -29,11 +30,12 @@ import org.apache.james.core.Username;
 import org.apache.james.user.api.UsersRepository;
 import org.apache.james.user.api.UsersRepositoryException;
 import org.apache.james.user.api.model.User;
-import org.apache.james.util.streams.Iterators;
 import org.apache.james.webadmin.dto.UserResponse;
 
 import com.google.common.collect.ImmutableList;
 
+import reactor.core.publisher.Flux;
+
 public class UserService {
     private final UsersRepository usersRepository;
 
@@ -42,13 +44,39 @@ public class UserService {
         this.usersRepository = usersRepository;
     }
 
-    public List<UserResponse> getUsers() throws UsersRepositoryException {
-        return  Optional.ofNullable(usersRepository.list())
-            .map(Iterators::toStream)
-            .orElse(Stream.of())
-            .map(Username::asString)
-            .map(UserResponse::new)
-            .collect(ImmutableList.toImmutableList());
+    /**
+     * Users sorted alphabetically, strictly after the anchor, optionally matching the query.
+     *
+     * The condition is applied after the repository pagination: repository pages are read until 'limit' users
+     * matching the condition are found, or the repository is exhausted.
+     */
+    public List<UserResponse> getUsers(Optional<String> query, Optional<Username> anchor, Optional<Integer> limit, Predicate<Username> condition) {
+        List<UserResponse> result = new ArrayList<>();
+        Optional<Username> pageAnchor = anchor;
+        while (true) {
+            List<Username> page = readPage(query, pageAnchor, limit);
+            page.stream()
+                .filter(condition)
+                .limit(limit.map(value -> value - result.size()).orElse(Integer.MAX_VALUE))
+                .map(Username::asString)
+                .map(UserResponse::new)
+                .forEach(result::add);
+
+            boolean exhausted = limit.map(value -> page.size() < value).orElse(true);
+            boolean full = limit.map(value -> result.size() >= value).orElse(false);
+            if (exhausted || full) {
+                return ImmutableList.copyOf(result);
+            }
+            pageAnchor = Optional.of(page.get(page.size() - 1));
+        }
+    }
+
+    private List<Username> readPage(Optional<String> query, Optional<Username> anchor, Optional<Integer> limit) {
+        return Flux.from(query
+                .map(q -> usersRepository.searchPaginated(q, anchor, limit))
+                .orElseGet(() -> usersRepository.listPaginated(anchor, limit)))
+            .collectList()
+            .block();
     }
 
     public void removeUser(Username username) throws UsersRepositoryException {
diff --git a/server/protocols/webadmin/webadmin-data/src/test/java/org/apache/james/webadmin/routes/UserRoutesTest.java b/server/protocols/webadmin/webadmin-data/src/test/java/org/apache/james/webadmin/routes/UserRoutesTest.java
index a9d2c27085..ebb10ef422 100644
--- a/server/protocols/webadmin/webadmin-data/src/test/java/org/apache/james/webadmin/routes/UserRoutesTest.java
+++ b/server/protocols/webadmin/webadmin-data/src/test/java/org/apache/james/webadmin/routes/UserRoutesTest.java
@@ -651,7 +651,7 @@ class UserRoutesTest {
 
             @Test
             default void getShouldFailOnRepositoryException(UsersRepository usersRepository) throws Exception {
-                when(usersRepository.list()).thenThrow(new UsersRepositoryException("message"));
+                when(usersRepository.listPaginated(any(), any())).thenReturn(Flux.error(new UsersRepositoryException("message")));
 
                 when()
                     .get()
@@ -713,7 +713,7 @@ class UserRoutesTest {
 
             @Test
             default void getShouldFailOnUnknownException(UsersRepository usersRepository) throws Exception {
-                when(usersRepository.list()).thenThrow(new RuntimeException());
+                when(usersRepository.listPaginated(any(), any())).thenThrow(new RuntimeException());
 
                 when()
                     .get()


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org


(james-project) 02/02: [ENHANCEMENT] GET /users: search by username prefix and domain via typed UsernamePredicate

Posted by rc...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

Arsnael pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/james-project.git

commit b8eabb3d9a3e4b8eebb13b8ad3429a2ae2baaff6
Author: Benoit TELLIER <bt...@linagora.com>
AuthorDate: Wed Oct 7 22:20:37 2026 +0200

    [ENHANCEMENT] GET /users: search by username prefix and domain via typed UsernamePredicate
---
 .../modules/servers/partials/operate/webadmin.adoc |   8 +-
 .../org/apache/james/user/api/UsersRepository.java |  48 ++----
 .../james/user/api/model/UsernamePredicate.java    |  73 ++++++++
 .../user/api/model/UsersPaginationHelpers.java     |  66 +++++++
 .../james/user/ldap/ReadOnlyLDAPUsersDAO.java      |  99 +++++++----
 .../ldap/ReadOnlyLDAPUsersDAOPaginationTest.java   | 192 +++++++++++++++++++++
 .../user/ldap/ReadOnlyUsersLDAPRepositoryTest.java |  80 +++++++++
 .../java/org/apache/james/user/lib/UsersDAO.java   |  21 +--
 .../apache/james/user/lib/UsersRepositoryImpl.java |  11 +-
 .../james/user/lib/UsersRepositoryContract.java    | 148 ++++++++++++++++
 .../apache/james/webadmin/routes/UserRoutes.java   |  36 +++-
 .../apache/james/webadmin/service/UserService.java |  46 ++---
 .../james/webadmin/routes/UserRoutesTest.java      |   5 +-
 13 files changed, 705 insertions(+), 128 deletions(-)

diff --git a/docs/modules/servers/partials/operate/webadmin.adoc b/docs/modules/servers/partials/operate/webadmin.adoc
index ad5527450f..52e02d19a1 100644
--- a/docs/modules/servers/partials/operate/webadmin.adoc
+++ b/docs/modules/servers/partials/operate/webadmin.adoc
@@ -699,17 +699,19 @@ curl -XGET http://ip:port/users?hasNoMailboxes
 curl -XGET http://ip:port/users?hasNotAllSystemMailboxes
 ....
 
-- `limit`, `anchor` and `query` allow paginating and searching the user list. Users are sorted alphabetically on their
+- `limit`, `anchor`, `query` and `domain` allow paginating and searching the user list. Users are sorted alphabetically on their
 username.
   - `limit`: maximum count of users returned (strictly positive integer). No limit if omitted.
   - `anchor`: only users whose username comes strictly after the anchor are returned. Pass the last username of the
 previous page to get the next one.
-  - `query`: only users whose username contains (case insensitively) this value are returned.
+  - `query`: only users whose username starts (case insensitively) with this value are returned.
+  - `domain`: only users of this domain are returned.
 
 ....
 curl -XGET http://ip:port/users?limit=50
 curl -XGET http://ip:port/users?limit=50&anchor=btellier@linagora.com
 curl -XGET http://ip:port/users?query=bte&limit=50&anchor=btellier@linagora.com
+curl -XGET http://ip:port/users?domain=linagora.com&limit=50
 ....
 
 These parameters can be combined with the condition parameters above.
@@ -717,7 +719,7 @@ These parameters can be combined with the condition parameters above.
 Response codes:
 
 * 200: The user name list was successfully retrieved
-* 400: Invalid `limit` or `anchor`
+* 400: Invalid `limit`, `anchor` or `domain`
 
 === Retrieving the list of allowed `From` headers for a given user
 
diff --git a/server/data/data-api/src/main/java/org/apache/james/user/api/UsersRepository.java b/server/data/data-api/src/main/java/org/apache/james/user/api/UsersRepository.java
index 5ccbd989f5..5ca1292cb4 100644
--- a/server/data/data-api/src/main/java/org/apache/james/user/api/UsersRepository.java
+++ b/server/data/data-api/src/main/java/org/apache/james/user/api/UsersRepository.java
@@ -19,15 +19,16 @@
 
 package org.apache.james.user.api;
 
-import java.util.Comparator;
 import java.util.Iterator;
-import java.util.Locale;
+import java.util.List;
 import java.util.Optional;
 
 import org.apache.james.core.Domain;
 import org.apache.james.core.MailAddress;
 import org.apache.james.core.Username;
 import org.apache.james.user.api.model.User;
+import org.apache.james.user.api.model.UsernamePredicate;
+import org.apache.james.user.api.model.UsersPaginationHelpers;
 import org.apache.james.util.ReactorUtils;
 import org.reactivestreams.Publisher;
 
@@ -189,47 +190,18 @@ public interface UsersRepository {
             .then();
     }
 
-    Comparator<Username> USERNAME_ALPHABETICAL_ORDER = Comparator.comparing(Username::asString);
-
-    /**
-     * Lists users sorted alphabetically on their username.
-     *
-     * @param anchor exclusive lower bound: only users strictly after it are returned
-     * @param limit maximum count of users returned, no limit if empty
-     */
-    default Publisher<Username> listPaginated(Optional<Username> anchor, Optional<Integer> limit) {
-        return applyLimit(Flux.from(listReactive())
-            .filter(username -> isAfter(username, anchor))
-            .sort(USERNAME_ALPHABETICAL_ORDER), limit);
-    }
-
     /**
-     * Lists users whose username contains (case insensitively) the query, sorted alphabetically on their username.
+     * Lists users matching all the predicates, sorted alphabetically on their username.
      *
-     * @param query substring the username needs to contain
+     * @param predicates criteria the users need to match, all users are listed when empty
      * @param anchor exclusive lower bound: only users strictly after it are returned
      * @param limit maximum count of users returned, no limit if empty
      */
-    default Publisher<Username> searchPaginated(String query, Optional<Username> anchor, Optional<Integer> limit) {
-        return applyLimit(Flux.from(listReactive())
-            .filter(username -> matches(username, query))
-            .filter(username -> isAfter(username, anchor))
-            .sort(USERNAME_ALPHABETICAL_ORDER), limit);
-    }
-
-    static Flux<Username> applyLimit(Flux<Username> usernames, Optional<Integer> limit) {
-        return limit.map(value -> usernames.take(value, true))
-            .orElse(usernames);
-    }
-
-    static boolean isAfter(Username username, Optional<Username> anchor) {
-        return anchor.map(a -> USERNAME_ALPHABETICAL_ORDER.compare(username, a) > 0)
-            .orElse(true);
-    }
-
-    static boolean matches(Username username, String query) {
-        return username.asString().toLowerCase(Locale.US)
-            .contains(query.toLowerCase(Locale.US));
+    default Publisher<Username> searchPaginated(List<UsernamePredicate> predicates, Optional<Username> anchor, Optional<Integer> limit) {
+        Publisher<Username> candidates = UsersPaginationHelpers.domain(predicates)
+            .<Publisher<Username>>map(this::listUsersOfADomainReactive)
+            .orElseGet(this::listReactive);
+        return UsersPaginationHelpers.paginate(candidates, predicates, anchor, limit);
     }
 
     default Publisher<Username> listUsersOfADomainReactive(Domain domain) {
diff --git a/server/data/data-api/src/main/java/org/apache/james/user/api/model/UsernamePredicate.java b/server/data/data-api/src/main/java/org/apache/james/user/api/model/UsernamePredicate.java
new file mode 100644
index 0000000000..f8305a468e
--- /dev/null
+++ b/server/data/data-api/src/main/java/org/apache/james/user/api/model/UsernamePredicate.java
@@ -0,0 +1,73 @@
+/****************************************************************
+ * 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.james.user.api.model;
+
+import java.util.Locale;
+import java.util.Objects;
+import java.util.function.Predicate;
+
+import org.apache.james.core.Domain;
+import org.apache.james.core.Username;
+
+import com.google.common.base.Preconditions;
+
+/**
+ * Typed criteria for searching users, allowing implementations to translate them into native queries.
+ */
+public sealed interface UsernamePredicate extends Predicate<Username> {
+    /**
+     * Matches users of the given domain.
+     */
+    record DomainPredicate(Domain domain) implements UsernamePredicate {
+        public DomainPredicate {
+            Objects.requireNonNull(domain);
+        }
+
+        @Override
+        public boolean test(Username username) {
+            return username.getDomainPart()
+                .map(domain::equals)
+                .orElse(false);
+        }
+    }
+
+    /**
+     * Matches users whose username starts (case insensitively) with the given prefix.
+     */
+    record UsernamePrefixPredicate(String prefix) implements UsernamePredicate {
+        public UsernamePrefixPredicate {
+            Preconditions.checkArgument(prefix != null && !prefix.isEmpty(), "'prefix' must not be empty");
+            prefix = prefix.toLowerCase(Locale.US);
+        }
+
+        @Override
+        public boolean test(Username username) {
+            return username.asString().toLowerCase(Locale.US).startsWith(prefix);
+        }
+    }
+
+    static DomainPredicate domain(Domain domain) {
+        return new DomainPredicate(domain);
+    }
+
+    static UsernamePrefixPredicate prefix(String prefix) {
+        return new UsernamePrefixPredicate(prefix);
+    }
+}
diff --git a/server/data/data-api/src/main/java/org/apache/james/user/api/model/UsersPaginationHelpers.java b/server/data/data-api/src/main/java/org/apache/james/user/api/model/UsersPaginationHelpers.java
new file mode 100644
index 0000000000..b17536893f
--- /dev/null
+++ b/server/data/data-api/src/main/java/org/apache/james/user/api/model/UsersPaginationHelpers.java
@@ -0,0 +1,66 @@
+/****************************************************************
+ * 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.james.user.api.model;
+
+import java.util.Comparator;
+import java.util.List;
+import java.util.Optional;
+
+import org.apache.james.core.Domain;
+import org.apache.james.core.Username;
+import org.reactivestreams.Publisher;
+
+import reactor.core.publisher.Flux;
+
+/**
+ * Helpers shared by the {@link org.apache.james.user.api.UsersRepository#searchPaginated} implementations.
+ */
+public final class UsersPaginationHelpers {
+    public static final Comparator<Username> USERNAME_ALPHABETICAL_ORDER = Comparator.comparing(Username::asString);
+
+    private UsersPaginationHelpers() {
+    }
+
+    public static Optional<Domain> domain(List<UsernamePredicate> predicates) {
+        return predicates.stream()
+            .filter(UsernamePredicate.DomainPredicate.class::isInstance)
+            .map(UsernamePredicate.DomainPredicate.class::cast)
+            .map(UsernamePredicate.DomainPredicate::domain)
+            .findFirst();
+    }
+
+    public static Flux<Username> paginate(Publisher<Username> users, List<UsernamePredicate> predicates, Optional<Username> anchor, Optional<Integer> limit) {
+        Flux<Username> sortedUsers = Flux.from(users)
+            .filter(username -> matchesAll(username, predicates))
+            .filter(username -> isAfter(username, anchor))
+            .sort(USERNAME_ALPHABETICAL_ORDER);
+        return limit.map(value -> sortedUsers.take(value, true))
+            .orElse(sortedUsers);
+    }
+
+    public static boolean matchesAll(Username username, List<UsernamePredicate> predicates) {
+        return predicates.stream().allMatch(predicate -> predicate.test(username));
+    }
+
+    public static boolean isAfter(Username username, Optional<Username> anchor) {
+        return anchor.map(a -> USERNAME_ALPHABETICAL_ORDER.compare(username, a) > 0)
+            .orElse(true);
+    }
+}
diff --git a/server/data/data-ldap/src/main/java/org/apache/james/user/ldap/ReadOnlyLDAPUsersDAO.java b/server/data/data-ldap/src/main/java/org/apache/james/user/ldap/ReadOnlyLDAPUsersDAO.java
index f1e20f054d..d229b106dd 100644
--- a/server/data/data-ldap/src/main/java/org/apache/james/user/ldap/ReadOnlyLDAPUsersDAO.java
+++ b/server/data/data-ldap/src/main/java/org/apache/james/user/ldap/ReadOnlyLDAPUsersDAO.java
@@ -27,6 +27,7 @@ import java.util.Map;
 import java.util.Optional;
 import java.util.Set;
 import java.util.TreeSet;
+import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.function.Consumer;
 import java.util.function.Predicate;
 import java.util.stream.Stream;
@@ -42,9 +43,10 @@ import org.apache.james.core.Domain;
 import org.apache.james.core.Username;
 import org.apache.james.lifecycle.api.Configurable;
 import org.apache.james.metrics.api.GaugeRegistry;
-import org.apache.james.user.api.UsersRepository;
 import org.apache.james.user.api.UsersRepositoryException;
 import org.apache.james.user.api.model.User;
+import org.apache.james.user.api.model.UsernamePredicate;
+import org.apache.james.user.api.model.UsersPaginationHelpers;
 import org.apache.james.user.lib.UsersDAO;
 import org.reactivestreams.Publisher;
 import org.slf4j.Logger;
@@ -62,6 +64,7 @@ import com.unboundid.ldap.sdk.Filter;
 import com.unboundid.ldap.sdk.LDAPConnection;
 import com.unboundid.ldap.sdk.LDAPConnectionPool;
 import com.unboundid.ldap.sdk.LDAPException;
+import com.unboundid.ldap.sdk.ResultCode;
 import com.unboundid.ldap.sdk.SearchRequest;
 import com.unboundid.ldap.sdk.SearchResult;
 import com.unboundid.ldap.sdk.SearchResultEntry;
@@ -211,8 +214,27 @@ public class ReadOnlyLDAPUsersDAO implements UsersDAO, Configurable {
     /**
      * Relies on the simple paged results control (RFC 2696) so that listing a large directory is not capped by the
      * server size limit. The paging cookie is bound to the LDAP connection thus all pages are read on the same connection.
+     *
+     * As the connection is not handled by the pool, we mimic its retry of operations failing due to an invalid connection
+     * (eg failover): the search is retried once on a new connection, as long as no entry was handed over yet.
      */
     private void pagedSearch(String dn, Filter filter, String attributes, Consumer<SearchResultEntry> entryConsumer) throws LDAPException {
+        AtomicBoolean entryHandedOver = new AtomicBoolean(false);
+        Consumer<SearchResultEntry> trackingConsumer = entry -> {
+            entryHandedOver.set(true);
+            entryConsumer.accept(entry);
+        };
+        try {
+            pagedSearchOnSingleConnection(dn, filter, attributes, trackingConsumer);
+        } catch (LDAPException e) {
+            if (ResultCode.isConnectionUsable(e.getResultCode()) || entryHandedOver.get()) {
+                throw e;
+            }
+            pagedSearchOnSingleConnection(dn, filter, attributes, entryConsumer);
+        }
+    }
+
+    private void pagedSearchOnSingleConnection(String dn, Filter filter, String attributes, Consumer<SearchResultEntry> entryConsumer) throws LDAPException {
         LDAPConnection connection = ldapConnectionPool.getConnection();
         try {
             ASN1OctetString cookie = null;
@@ -393,48 +415,63 @@ public class ReadOnlyLDAPUsersDAO implements UsersDAO, Configurable {
 
 
     @Override
-    public Publisher<Username> listPaginated(Optional<Username> anchor, Optional<Integer> limit) {
-        if (ldapConfiguration.getRestriction().isActivated()) {
-            return UsersDAO.super.listPaginated(anchor, limit);
-        }
-        return firstUsernamesAfter(listingFilter, username -> true, anchor, limit);
-    }
-
-    @Override
-    public Publisher<Username> searchPaginated(String query, Optional<Username> anchor, Optional<Integer> limit) {
+    public Publisher<Username> searchPaginated(List<UsernamePredicate> predicates, Optional<Username> anchor, Optional<Integer> limit) {
         if (ldapConfiguration.getRestriction().isActivated()) {
-            return UsersDAO.super.searchPaginated(query, anchor, limit);
+            return UsersDAO.super.searchPaginated(predicates, anchor, limit);
         }
-        Filter queryFilter = Filter.createSubstringFilter(usernameAttribute(), null, new String[]{query}, null);
-        return firstUsernamesAfter(Filter.createANDFilter(listingFilter, queryFilter),
-            username -> UsersRepository.matches(username, query), anchor, limit);
+        String usernameAttribute = usernameAttribute();
+        Filter filter = Filter.createANDFilter(ImmutableList.<Filter>builder()
+            .add(listingFilter)
+            .addAll(predicates.stream()
+                .map(predicate -> asLdapFilter(predicate, usernameAttribute))
+                .toList())
+            .build());
+        // Only the base DN of the searched domain needs to be scanned
+        List<String> dns = UsersPaginationHelpers.domain(predicates)
+            .map(domain -> List.of(userBase(domain)))
+            .orElseGet(() -> allDNs().toList());
+        return firstUsernamesAfter(dns, filter, username -> UsersPaginationHelpers.matchesAll(username, predicates), anchor, limit);
+    }
+
+    private Filter asLdapFilter(UsernamePredicate predicate, String usernameAttribute) {
+        return switch (predicate) {
+            case UsernamePredicate.DomainPredicate domainPredicate ->
+                Filter.createSubstringFilter(usernameAttribute, null, null, "@" + domainPredicate.domain().asString());
+            case UsernamePredicate.UsernamePrefixPredicate prefixPredicate ->
+                Filter.createSubstringFilter(usernameAttribute, prefixPredicate.prefix(), null, null);
+        };
     }
 
     /**
      * Only the username attribute is retrieved, and only the 'limit' first usernames after the anchor are retained
      * in memory while the (paged) LDAP search results are being read.
      */
-    private Flux<Username> firstUsernamesAfter(Filter filter, Predicate<Username> predicate, Optional<Username> anchor, Optional<Integer> limit) {
-        String usernameAttribute = usernameAttribute();
-        return Mono.fromCallable(() -> {
-                TreeSet<Username> firstUsernames = new TreeSet<>(UsersRepository.USERNAME_ALPHABETICAL_ORDER);
-                for (String dn : allDNs().toList()) {
-                    pagedSearch(dn, filter, usernameAttribute, entry -> asUsername(entry, usernameAttribute)
-                        .filter(predicate)
-                        .filter(username -> UsersRepository.isAfter(username, anchor))
-                        .ifPresent(username -> {
-                            firstUsernames.add(username);
-                            if (limit.isPresent() && firstUsernames.size() > limit.get()) {
-                                firstUsernames.pollLast();
-                            }
-                        }));
-                }
-                return firstUsernames;
-            })
+    private Flux<Username> firstUsernamesAfter(List<String> dns, Filter filter, Predicate<Username> predicate, Optional<Username> anchor, Optional<Integer> limit) {
+        return Mono.fromCallable(() -> collectFirstUsernamesAfter(dns, filter, predicate, anchor, limit))
             .flatMapIterable(usernames -> usernames)
             .subscribeOn(Schedulers.boundedElastic());
     }
 
+    private TreeSet<Username> collectFirstUsernamesAfter(List<String> dns, Filter filter, Predicate<Username> predicate,
+                                                         Optional<Username> anchor, Optional<Integer> limit) throws LDAPException {
+        String usernameAttribute = usernameAttribute();
+        TreeSet<Username> firstUsernames = new TreeSet<>(UsersPaginationHelpers.USERNAME_ALPHABETICAL_ORDER);
+        for (String dn : dns) {
+            pagedSearch(dn, filter, usernameAttribute, entry -> asUsername(entry, usernameAttribute)
+                .filter(predicate)
+                .filter(username -> UsersPaginationHelpers.isAfter(username, anchor))
+                .ifPresent(username -> addWithinLimit(firstUsernames, username, limit)));
+        }
+        return firstUsernames;
+    }
+
+    private static void addWithinLimit(TreeSet<Username> firstUsernames, Username username, Optional<Integer> limit) {
+        firstUsernames.add(username);
+        if (limit.isPresent() && firstUsernames.size() > limit.get()) {
+            firstUsernames.pollLast();
+        }
+    }
+
     @Override
     public Flux<Username> listUsersOfADomainReactive(Domain domain, boolean supportsVirtualHosting) {
         return Flux.fromStream(() -> {
diff --git a/server/data/data-ldap/src/test/java/org/apache/james/user/ldap/ReadOnlyLDAPUsersDAOPaginationTest.java b/server/data/data-ldap/src/test/java/org/apache/james/user/ldap/ReadOnlyLDAPUsersDAOPaginationTest.java
new file mode 100644
index 0000000000..1042110bb7
--- /dev/null
+++ b/server/data/data-ldap/src/test/java/org/apache/james/user/ldap/ReadOnlyLDAPUsersDAOPaginationTest.java
@@ -0,0 +1,192 @@
+/****************************************************************
+ * 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.james.user.ldap;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+import org.apache.james.core.Domain;
+import org.apache.james.core.Username;
+import org.apache.james.metrics.api.NoopGaugeRegistry;
+import org.apache.james.user.api.model.UsernamePredicate;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import com.google.common.collect.ImmutableList;
+import com.unboundid.ldap.listener.InMemoryDirectoryServer;
+import com.unboundid.ldap.listener.InMemoryDirectoryServerConfig;
+import com.unboundid.ldap.sdk.LDAPConnectionPool;
+
+import reactor.core.publisher.Flux;
+
+class ReadOnlyLDAPUsersDAOPaginationTest {
+    static final String BASE_DN = "dc=james,dc=org";
+    static final String PEOPLE_DN = "ou=people," + BASE_DN;
+    // More users than the server size limit, so that listing them can not rely on a single search
+    static final List<Username> JAMES_USERS = IntStream.range(0, 560)
+        .mapToObj(i -> Username.of(String.format("user%03d@james.org", i)))
+        .collect(ImmutableList.toImmutableList());
+    static final List<Username> OTHER_USERS = IntStream.range(0, 10)
+        .mapToObj(i -> Username.of(String.format("other%03d@other.org", i)))
+        .collect(ImmutableList.toImmutableList());
+    static final List<Username> ALL_USERS = Stream.concat(OTHER_USERS.stream(), JAMES_USERS.stream())
+        .collect(ImmutableList.toImmutableList());
+    // Matches the OpenLDAP default size limit
+    static final int SERVER_SIZE_LIMIT = 500;
+
+    InMemoryDirectoryServer ldapServer;
+    LDAPConnectionPool connectionPool;
+    ReadOnlyLDAPUsersDAO testee;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        InMemoryDirectoryServerConfig serverConfig = new InMemoryDirectoryServerConfig(BASE_DN);
+        serverConfig.setMaxSizeLimit(SERVER_SIZE_LIMIT);
+        ldapServer = new InMemoryDirectoryServer(serverConfig);
+        ldapServer.startListening();
+        ldapServer.add("dn: " + BASE_DN, "objectClass: domain", "dc: james");
+        ldapServer.add("dn: " + PEOPLE_DN, "objectClass: organizationalUnit", "ou: people");
+        for (Username username : ALL_USERS) {
+            String localPart = username.getLocalPart();
+            ldapServer.add("dn: uid=" + localPart + "-" + username.getDomainPart().get().asString() + "," + PEOPLE_DN,
+                "objectClass: inetOrgPerson",
+                "uid: " + localPart,
+                "cn: " + localPart,
+                "sn: " + localPart,
+                "mail: " + username.asString());
+        }
+
+        LdapRepositoryConfiguration configuration = LdapRepositoryConfiguration.builder()
+            .ldapHosts(ImmutableList.of(URI.create("ldap://127.0.0.1:" + ldapServer.getListenPort())))
+            .principal("")
+            .credentials("")
+            .userBase(PEOPLE_DN)
+            .userIdAttribute("mail")
+            .userObjectClass("inetOrgPerson")
+            .build();
+
+        connectionPool = ldapServer.getConnectionPool(2);
+        testee = new ReadOnlyLDAPUsersDAO(new NoopGaugeRegistry(), connectionPool, configuration);
+        testee.init();
+    }
+
+    @AfterEach
+    void tearDown() {
+        connectionPool.close();
+        ldapServer.shutDown(true);
+    }
+
+    List<Username> search(List<UsernamePredicate> predicates, Optional<Username> anchor, Optional<Integer> limit) {
+        return Flux.from(testee.searchPaginated(predicates, anchor, limit))
+            .collectList()
+            .block();
+    }
+
+    @Test
+    void shouldReturnFirstUsersSortedAlphabetically() {
+        assertThat(search(ImmutableList.of(), Optional.empty(), Optional.of(5)))
+            .containsExactlyElementsOf(ALL_USERS.subList(0, 5));
+    }
+
+    @Test
+    void shouldReturnAllUsersSortedWhenNoLimit() {
+        assertThat(search(ImmutableList.of(), Optional.empty(), Optional.empty()))
+            .containsExactlyElementsOf(ALL_USERS);
+    }
+
+    @Test
+    void shouldReturnUsersStrictlyAfterTheAnchor() {
+        assertThat(search(ImmutableList.of(), Optional.of(ALL_USERS.get(10)), Optional.of(3)))
+            .containsExactlyElementsOf(ALL_USERS.subList(11, 14));
+    }
+
+    @Test
+    void shouldSupportAnAnchorNotInTheDirectory() {
+        // "user0505@" sorts before "user050@" as '5' < '@'
+        assertThat(search(ImmutableList.of(), Optional.of(Username.of("user0505@james.org")), Optional.of(2)))
+            .containsExactly(Username.of("user050@james.org"), Username.of("user051@james.org"));
+    }
+
+    @Test
+    void shouldReturnLessUsersThanTheLimitOnTheLastPage() {
+        assertThat(search(ImmutableList.of(), Optional.of(ALL_USERS.get(ALL_USERS.size() - 3)), Optional.of(10)))
+            .containsExactlyElementsOf(ALL_USERS.subList(ALL_USERS.size() - 2, ALL_USERS.size()));
+    }
+
+    @Test
+    void shouldReturnNoUsersAfterTheLastOne() {
+        assertThat(search(ImmutableList.of(), Optional.of(ALL_USERS.getLast()), Optional.of(10)))
+            .isEmpty();
+    }
+
+    @Test
+    void browsingAllPagesShouldReturnAllUsersOnce() {
+        List<Username> browsed = new ArrayList<>();
+        Optional<Username> anchor = Optional.empty();
+        while (true) {
+            List<Username> page = search(ImmutableList.of(), anchor, Optional.of(50));
+            browsed.addAll(page);
+            if (page.size() < 50) {
+                break;
+            }
+            anchor = Optional.of(page.getLast());
+        }
+
+        assertThat(browsed).containsExactlyElementsOf(ALL_USERS);
+    }
+
+    @Test
+    void shouldFilterByPrefix() {
+        assertThat(search(ImmutableList.of(UsernamePredicate.prefix("user11")), Optional.empty(), Optional.of(50)))
+            .containsExactlyElementsOf(JAMES_USERS.subList(110, 120));
+    }
+
+    @Test
+    void prefixShouldBeCaseInsensitive() {
+        assertThat(search(ImmutableList.of(UsernamePredicate.prefix("USER11")), Optional.empty(), Optional.of(50)))
+            .containsExactlyElementsOf(JAMES_USERS.subList(110, 120));
+    }
+
+    @Test
+    void shouldFilterByDomain() {
+        assertThat(search(ImmutableList.of(UsernamePredicate.domain(Domain.of("other.org"))), Optional.empty(), Optional.of(50)))
+            .containsExactlyElementsOf(OTHER_USERS);
+    }
+
+    @Test
+    void shouldCombinePredicatesAnchorAndLimit() {
+        assertThat(search(ImmutableList.of(UsernamePredicate.domain(Domain.of("james.org")), UsernamePredicate.prefix("user1")),
+                Optional.of(Username.of("user104@james.org")), Optional.of(3)))
+            .containsExactly(Username.of("user105@james.org"), Username.of("user106@james.org"), Username.of("user107@james.org"));
+    }
+
+    @Test
+    void shouldReturnNothingWhenNoMatch() {
+        assertThat(search(ImmutableList.of(UsernamePredicate.prefix("nobody")), Optional.empty(), Optional.of(10)))
+            .isEmpty();
+    }
+}
diff --git a/server/data/data-ldap/src/test/java/org/apache/james/user/ldap/ReadOnlyUsersLDAPRepositoryTest.java b/server/data/data-ldap/src/test/java/org/apache/james/user/ldap/ReadOnlyUsersLDAPRepositoryTest.java
index 440f2256e0..0ff348f245 100644
--- a/server/data/data-ldap/src/test/java/org/apache/james/user/ldap/ReadOnlyUsersLDAPRepositoryTest.java
+++ b/server/data/data-ldap/src/test/java/org/apache/james/user/ldap/ReadOnlyUsersLDAPRepositoryTest.java
@@ -28,6 +28,7 @@ import static org.apache.james.user.ldap.DockerLdapSingleton.PASSWORD;
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 
+import java.util.List;
 import java.util.Optional;
 import java.util.Set;
 
@@ -41,6 +42,7 @@ import org.apache.james.domainlist.api.DomainList;
 import org.apache.james.domainlist.api.mock.SimpleDomainList;
 import org.apache.james.metrics.api.NoopGaugeRegistry;
 import org.apache.james.user.api.UsersRepository;
+import org.apache.james.user.api.model.UsernamePredicate;
 import org.apache.james.user.lib.UsersRepositoryContract;
 import org.apache.james.user.lib.UsersRepositoryImpl;
 import org.awaitility.Awaitility;
@@ -137,6 +139,42 @@ class ReadOnlyUsersLDAPRepositoryTest {
             assertThat(ImmutableList.copyOf(usersLDAPRepository.list()))
                 .containsOnly(JAMES_USER_MAIL, Username.of("bob@extra.org"));
         }
+
+        @Test
+        void searchPaginatedShouldListUsersOfAllDNsSorted() {
+            assertThat(searchPaginated(usersLDAPRepository, ImmutableList.of(), Optional.empty(), Optional.empty()))
+                .containsExactly(Username.of("bob@extra.org"), JAMES_USER_MAIL);
+        }
+
+        @Test
+        void searchPaginatedShouldApplyAnchorAndLimitAcrossDNs() {
+            assertThat(searchPaginated(usersLDAPRepository, ImmutableList.of(), Optional.of(Username.of("bob@extra.org")), Optional.of(1)))
+                .containsExactly(JAMES_USER_MAIL);
+        }
+
+        @Test
+        void searchPaginatedShouldFilterByDomainOfAnExtraDN() {
+            assertThat(searchPaginated(usersLDAPRepository, ImmutableList.of(UsernamePredicate.domain(Domain.of("extra.org"))), Optional.empty(), Optional.empty()))
+                .containsExactly(Username.of("bob@extra.org"));
+        }
+
+        @Test
+        void searchPaginatedShouldFilterByMainDomain() {
+            assertThat(searchPaginated(usersLDAPRepository, ImmutableList.of(UsernamePredicate.domain(Domain.of(DOMAIN))), Optional.empty(), Optional.empty()))
+                .containsExactly(JAMES_USER_MAIL);
+        }
+
+        @Test
+        void searchPaginatedShouldReturnEmptyForUnknownDomain() {
+            assertThat(searchPaginated(usersLDAPRepository, ImmutableList.of(UsernamePredicate.domain(Domain.of("nonexistant.org"))), Optional.empty(), Optional.empty()))
+                .isEmpty();
+        }
+
+        @Test
+        void searchPaginatedShouldFilterByPrefixIgnoringCase() {
+            assertThat(searchPaginated(usersLDAPRepository, ImmutableList.of(UsernamePredicate.prefix("JAMES")), Optional.empty(), Optional.empty()))
+                .containsExactly(JAMES_USER_MAIL);
+        }
     }
 
     @Nested
@@ -182,6 +220,13 @@ class ReadOnlyUsersLDAPRepositoryTest {
             // james-user@james.org is not in userListBase thus is not listed
             assertThat(ImmutableList.copyOf(usersLDAPRepository.list())).containsOnly(Username.of("bob@extra.org"));
         }
+
+        @Test
+        void searchPaginatedShouldListEntriesInUserListBase() {
+            // james-user@james.org is not in userListBase thus is not listed
+            assertThat(searchPaginated(usersLDAPRepository, ImmutableList.of(), Optional.empty(), Optional.empty()))
+                .containsExactly(Username.of("bob@extra.org"));
+        }
     }
 
     @Nested
@@ -237,6 +282,34 @@ class ReadOnlyUsersLDAPRepositoryTest {
 
             assertThat(ImmutableList.copyOf(usersLDAPRepository.list())).isEmpty();
         }
+
+        @Test
+        void searchPaginatedShouldKeepMatchingEntries() throws Exception {
+            HierarchicalConfiguration<ImmutableNode> configuration = ldapRepositoryConfiguration(ldapContainer);
+            configuration.addProperty("[@filter]", "(sn=james-user)");
+
+            ReadOnlyUsersLDAPRepository usersLDAPRepository = new ReadOnlyUsersLDAPRepository(new SimpleDomainList(), new NoopGaugeRegistry(),
+                LdapRepositoryConfiguration.from(configuration));
+            usersLDAPRepository.configure(configuration);
+            usersLDAPRepository.init();
+
+            assertThat(searchPaginated(usersLDAPRepository, ImmutableList.of(UsernamePredicate.prefix("james")), Optional.empty(), Optional.of(10)))
+                .containsExactly(JAMES_USER);
+        }
+
+        @Test
+        void searchPaginatedShouldTakeFilterIntoAccount() throws Exception {
+            HierarchicalConfiguration<ImmutableNode> configuration = ldapRepositoryConfiguration(ldapContainer);
+            configuration.addProperty("[@filter]", "(sn=nomatch)");
+
+            ReadOnlyUsersLDAPRepository usersLDAPRepository = new ReadOnlyUsersLDAPRepository(new SimpleDomainList(), new NoopGaugeRegistry(),
+                LdapRepositoryConfiguration.from(configuration));
+            usersLDAPRepository.configure(configuration);
+            usersLDAPRepository.init();
+
+            assertThat(searchPaginated(usersLDAPRepository, ImmutableList.of(), Optional.empty(), Optional.of(10)))
+                .isEmpty();
+        }
     }
 
     @Nested
@@ -573,6 +646,13 @@ class ReadOnlyUsersLDAPRepositoryTest {
         return ldapRepository;
     }
 
+    static List<Username> searchPaginated(UsersRepository usersRepository, List<UsernamePredicate> predicates,
+                                          Optional<Username> anchor, Optional<Integer> limit) {
+        return Flux.from(usersRepository.searchPaginated(predicates, anchor, limit))
+            .collectList()
+            .block();
+    }
+
     static HierarchicalConfiguration<ImmutableNode> ldapRepositoryConfiguration(LdapGenericContainer ldapContainer) {
         return ldapRepositoryConfiguration(ldapContainer, Optional.of(Username.of(ADMIN_LOCAL_PART)));
     }
diff --git a/server/data/data-library/src/main/java/org/apache/james/user/lib/UsersDAO.java b/server/data/data-library/src/main/java/org/apache/james/user/lib/UsersDAO.java
index f18b52cf74..1445505b0c 100644
--- a/server/data/data-library/src/main/java/org/apache/james/user/lib/UsersDAO.java
+++ b/server/data/data-library/src/main/java/org/apache/james/user/lib/UsersDAO.java
@@ -20,13 +20,15 @@
 package org.apache.james.user.lib;
 
 import java.util.Iterator;
+import java.util.List;
 import java.util.Optional;
 
 import org.apache.james.core.Domain;
 import org.apache.james.core.Username;
-import org.apache.james.user.api.UsersRepository;
 import org.apache.james.user.api.UsersRepositoryException;
 import org.apache.james.user.api.model.User;
+import org.apache.james.user.api.model.UsernamePredicate;
+import org.apache.james.user.api.model.UsersPaginationHelpers;
 import org.apache.james.util.ReactorUtils;
 import org.reactivestreams.Publisher;
 
@@ -73,17 +75,12 @@ public interface UsersDAO {
                 .orElse(!supportsVirtualHosting));
     }
 
-    default Publisher<Username> listPaginated(Optional<Username> anchor, Optional<Integer> limit) {
-        return UsersRepository.applyLimit(Flux.from(listReactive())
-            .filter(username -> UsersRepository.isAfter(username, anchor))
-            .sort(UsersRepository.USERNAME_ALPHABETICAL_ORDER), limit);
-    }
-
-    default Publisher<Username> searchPaginated(String query, Optional<Username> anchor, Optional<Integer> limit) {
-        return UsersRepository.applyLimit(Flux.from(listReactive())
-            .filter(username -> UsersRepository.matches(username, query))
-            .filter(username -> UsersRepository.isAfter(username, anchor))
-            .sort(UsersRepository.USERNAME_ALPHABETICAL_ORDER), limit);
+    default Publisher<Username> searchPaginated(List<UsernamePredicate> predicates, Optional<Username> anchor, Optional<Integer> limit) {
+        // DomainPredicate only matches usernames having a domain part, hence virtual hosting can be assumed
+        Publisher<Username> candidates = UsersPaginationHelpers.domain(predicates)
+            .map(domain -> listUsersOfADomainReactive(domain, true))
+            .orElseGet(this::listReactive);
+        return UsersPaginationHelpers.paginate(candidates, predicates, anchor, limit);
     }
 
     void addUser(Username username, String password) throws UsersRepositoryException;
diff --git a/server/data/data-library/src/main/java/org/apache/james/user/lib/UsersRepositoryImpl.java b/server/data/data-library/src/main/java/org/apache/james/user/lib/UsersRepositoryImpl.java
index bc0bcf1780..a548c56076 100644
--- a/server/data/data-library/src/main/java/org/apache/james/user/lib/UsersRepositoryImpl.java
+++ b/server/data/data-library/src/main/java/org/apache/james/user/lib/UsersRepositoryImpl.java
@@ -22,6 +22,7 @@ package org.apache.james.user.lib;
 import java.time.temporal.ChronoUnit;
 import java.util.Arrays;
 import java.util.Iterator;
+import java.util.List;
 import java.util.Objects;
 import java.util.Optional;
 import java.util.Set;
@@ -44,6 +45,7 @@ import org.apache.james.user.api.InvalidUsernameException;
 import org.apache.james.user.api.UsersRepository;
 import org.apache.james.user.api.UsersRepositoryException;
 import org.apache.james.user.api.model.User;
+import org.apache.james.user.api.model.UsernamePredicate;
 import org.apache.james.util.DurationParser;
 import org.reactivestreams.Publisher;
 import org.slf4j.LoggerFactory;
@@ -263,13 +265,8 @@ public class UsersRepositoryImpl<T extends UsersDAO> implements UsersRepository,
     }
 
     @Override
-    public Publisher<Username> listPaginated(Optional<Username> anchor, Optional<Integer> limit) {
-        return usersDAO.listPaginated(anchor, limit);
-    }
-
-    @Override
-    public Publisher<Username> searchPaginated(String query, Optional<Username> anchor, Optional<Integer> limit) {
-        return usersDAO.searchPaginated(query, anchor, limit);
+    public Publisher<Username> searchPaginated(List<UsernamePredicate> predicates, Optional<Username> anchor, Optional<Integer> limit) {
+        return usersDAO.searchPaginated(predicates, anchor, limit);
     }
 
     @Override
diff --git a/server/data/data-library/src/test/java/org/apache/james/user/lib/UsersRepositoryContract.java b/server/data/data-library/src/test/java/org/apache/james/user/lib/UsersRepositoryContract.java
index 22c64045ad..645b9d05a2 100644
--- a/server/data/data-library/src/test/java/org/apache/james/user/lib/UsersRepositoryContract.java
+++ b/server/data/data-library/src/test/java/org/apache/james/user/lib/UsersRepositoryContract.java
@@ -22,7 +22,9 @@ import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.api.Assertions.assertThatCode;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 
+import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Comparator;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Optional;
@@ -38,6 +40,7 @@ import org.apache.james.user.api.InvalidUsernameException;
 import org.apache.james.user.api.UsersRepository;
 import org.apache.james.user.api.UsersRepositoryException;
 import org.apache.james.user.api.model.User;
+import org.apache.james.user.api.model.UsernamePredicate;
 import org.apache.james.user.lib.model.Algorithm;
 import org.apache.james.user.lib.model.DefaultUser;
 import org.junit.jupiter.api.Assumptions;
@@ -51,6 +54,8 @@ import org.junit.jupiter.params.ParameterizedTest;
 import org.junit.jupiter.params.provider.Arguments;
 import org.junit.jupiter.params.provider.MethodSource;
 
+import com.google.common.collect.ImmutableList;
+
 import reactor.core.publisher.Flux;
 
 public interface UsersRepositoryContract {
@@ -249,6 +254,112 @@ public interface UsersRepositoryContract {
                 .containsOnly(testSystem.user1, testSystem.user2, testSystem.user3);
         }
 
+        default List<Username> searchPaginated(List<UsernamePredicate> predicates, Optional<Username> anchor, Optional<Integer> limit) {
+            return Flux.from(testee().searchPaginated(predicates, anchor, limit))
+                .collectList()
+                .block();
+        }
+
+        default List<Username> addUsers(TestSystem testSystem, String... localParts) throws UsersRepositoryException {
+            ImmutableList.Builder<Username> usernames = ImmutableList.builder();
+            for (String localPart : localParts) {
+                Username username = testSystem.toUsername(localPart);
+                testee().addUser(username, "password");
+                usernames.add(username);
+            }
+            return usernames.build().stream()
+                .sorted(Comparator.comparing(Username::asString))
+                .collect(ImmutableList.toImmutableList());
+        }
+
+        @Test
+        default void searchPaginatedShouldReturnEmptyWhenEmptyRepository() {
+            assertThat(searchPaginated(ImmutableList.of(), Optional.empty(), Optional.empty()))
+                .isEmpty();
+        }
+
+        @Test
+        default void searchPaginatedShouldReturnAllUsersSortedAlphabetically(TestSystem testSystem) throws UsersRepositoryException {
+            List<Username> sortedUsers = addUsers(testSystem, "charlie", "alice", "bob");
+
+            assertThat(searchPaginated(ImmutableList.of(), Optional.empty(), Optional.empty()))
+                .containsExactlyElementsOf(sortedUsers);
+        }
+
+        @Test
+        default void searchPaginatedShouldApplyTheLimit(TestSystem testSystem) throws UsersRepositoryException {
+            List<Username> sortedUsers = addUsers(testSystem, "charlie", "alice", "bob");
+
+            assertThat(searchPaginated(ImmutableList.of(), Optional.empty(), Optional.of(2)))
+                .containsExactlyElementsOf(sortedUsers.subList(0, 2));
+        }
+
+        @Test
+        default void searchPaginatedShouldReturnUsersStrictlyAfterTheAnchor(TestSystem testSystem) throws UsersRepositoryException {
+            List<Username> sortedUsers = addUsers(testSystem, "charlie", "alice", "bob", "dave");
+
+            assertThat(searchPaginated(ImmutableList.of(), Optional.of(sortedUsers.get(1)), Optional.of(1)))
+                .containsExactly(sortedUsers.get(2));
+        }
+
+        @Test
+        default void searchPaginatedShouldAcceptAnAnchorThatIsNotAUser(TestSystem testSystem) throws UsersRepositoryException {
+            List<Username> sortedUsers = addUsers(testSystem, "alice", "charlie");
+
+            assertThat(searchPaginated(ImmutableList.of(), Optional.of(testSystem.toUsername("bob")), Optional.empty()))
+                .containsExactly(sortedUsers.get(1));
+        }
+
+        @Test
+        default void searchPaginatedShouldReturnEmptyAfterTheLastUser(TestSystem testSystem) throws UsersRepositoryException {
+            List<Username> sortedUsers = addUsers(testSystem, "alice", "bob");
+
+            assertThat(searchPaginated(ImmutableList.of(), Optional.of(sortedUsers.getLast()), Optional.of(10)))
+                .isEmpty();
+        }
+
+        @Test
+        default void browsingPagesShouldReturnAllUsersOnce(TestSystem testSystem) throws UsersRepositoryException {
+            List<Username> sortedUsers = addUsers(testSystem, "user1", "user2", "user3", "user4", "user5", "user6", "user7");
+
+            List<Username> browsed = new ArrayList<>();
+            Optional<Username> anchor = Optional.empty();
+            while (true) {
+                List<Username> page = searchPaginated(ImmutableList.of(), anchor, Optional.of(3));
+                browsed.addAll(page);
+                if (page.size() < 3) {
+                    break;
+                }
+                anchor = Optional.of(page.getLast());
+            }
+
+            assertThat(browsed).containsExactlyElementsOf(sortedUsers);
+        }
+
+        @Test
+        default void searchPaginatedShouldFilterByPrefix(TestSystem testSystem) throws UsersRepositoryException {
+            addUsers(testSystem, "albert", "bob", "alice");
+
+            assertThat(searchPaginated(ImmutableList.of(UsernamePredicate.prefix("al")), Optional.empty(), Optional.empty()))
+                .containsExactly(testSystem.toUsername("albert"), testSystem.toUsername("alice"));
+        }
+
+        @Test
+        default void searchPaginatedPrefixShouldBeCaseInsensitive(TestSystem testSystem) throws UsersRepositoryException {
+            addUsers(testSystem, "albert", "bob");
+
+            assertThat(searchPaginated(ImmutableList.of(UsernamePredicate.prefix("AL")), Optional.empty(), Optional.empty()))
+                .containsExactly(testSystem.toUsername("albert"));
+        }
+
+        @Test
+        default void searchPaginatedShouldCombinePrefixAnchorAndLimit(TestSystem testSystem) throws UsersRepositoryException {
+            addUsers(testSystem, "alan", "albert", "alice", "alvin", "bob");
+
+            assertThat(searchPaginated(ImmutableList.of(UsernamePredicate.prefix("al")), Optional.of(testSystem.toUsername("albert")), Optional.of(2)))
+                .containsExactly(testSystem.toUsername("alice"), testSystem.toUsername("alvin"));
+        }
+
         @Test
         default void addUserShouldAddAUserWhenEmptyRepository(TestSystem testSystem) throws UsersRepositoryException {
             //When
@@ -604,6 +715,43 @@ public interface UsersRepositoryContract {
                 .containsExactlyInAnyOrder(Username.of("alice@domain.tld"), Username.of("bob@domain.tld"));
         }
 
+        @Test
+        default void searchPaginatedShouldFilterByDomain(TestSystem testSystem) throws Exception {
+            testSystem.domainList.addDomain(Domain.of("domain1.tld"));
+            testSystem.domainList.addDomain(Domain.of("domain2.tld"));
+            testee().addUser(Username.of("bob@domain1.tld"), "password");
+            testee().addUser(Username.of("alice@domain1.tld"), "password");
+            testee().addUser(Username.of("alice@domain2.tld"), "password");
+
+            assertThat(searchPaginated(ImmutableList.of(UsernamePredicate.domain(Domain.of("domain1.tld"))), Optional.empty(), Optional.empty()))
+                .containsExactly(Username.of("alice@domain1.tld"), Username.of("bob@domain1.tld"));
+        }
+
+        @Test
+        default void searchPaginatedShouldReturnEmptyWhenNoUserInDomain(TestSystem testSystem) throws Exception {
+            testSystem.domainList.addDomain(Domain.of("empty.tld"));
+            testee().addUser(testSystem.user1, "password");
+
+            assertThat(searchPaginated(ImmutableList.of(UsernamePredicate.domain(Domain.of("empty.tld"))), Optional.empty(), Optional.empty()))
+                .isEmpty();
+        }
+
+        @Test
+        default void searchPaginatedShouldCombineDomainPrefixAnchorAndLimit(TestSystem testSystem) throws Exception {
+            testSystem.domainList.addDomain(Domain.of("domain1.tld"));
+            testSystem.domainList.addDomain(Domain.of("domain2.tld"));
+            testee().addUser(Username.of("alan@domain1.tld"), "password");
+            testee().addUser(Username.of("albert@domain1.tld"), "password");
+            testee().addUser(Username.of("alice@domain1.tld"), "password");
+            testee().addUser(Username.of("alvin@domain1.tld"), "password");
+            testee().addUser(Username.of("alice@domain2.tld"), "password");
+            testee().addUser(Username.of("bob@domain1.tld"), "password");
+
+            assertThat(searchPaginated(ImmutableList.of(UsernamePredicate.domain(Domain.of("domain1.tld")), UsernamePredicate.prefix("al")),
+                    Optional.of(Username.of("alan@domain1.tld")), Optional.of(2)))
+                .containsExactly(Username.of("albert@domain1.tld"), Username.of("alice@domain1.tld"));
+        }
+
         @Test
         default void addUserShouldThrowWhenUserDoesNotBelongToDomainList(TestSystem testSystem) {
             assertThatThrownBy(() -> testee().addUser(testSystem.userWithUnknownDomain, "password"))
diff --git a/server/protocols/webadmin/webadmin-data/src/main/java/org/apache/james/webadmin/routes/UserRoutes.java b/server/protocols/webadmin/webadmin-data/src/main/java/org/apache/james/webadmin/routes/UserRoutes.java
index b62e4b1b94..1d7460f38c 100644
--- a/server/protocols/webadmin/webadmin-data/src/main/java/org/apache/james/webadmin/routes/UserRoutes.java
+++ b/server/protocols/webadmin/webadmin-data/src/main/java/org/apache/james/webadmin/routes/UserRoutes.java
@@ -20,16 +20,17 @@
 package org.apache.james.webadmin.routes;
 
 import static org.apache.james.webadmin.Constants.SEPARATOR;
-import static org.apache.james.webadmin.UserCondition.ALL;
 import static spark.Spark.halt;
 
 import java.util.List;
 import java.util.Map;
 import java.util.Optional;
+import java.util.stream.Stream;
 
 import jakarta.inject.Inject;
 
 import org.apache.commons.lang3.NotImplementedException;
+import org.apache.james.core.Domain;
 import org.apache.james.core.MailAddress;
 import org.apache.james.core.Username;
 import org.apache.james.rrt.api.CanSendFrom;
@@ -39,6 +40,7 @@ import org.apache.james.user.api.AlreadyExistInUsersRepositoryException;
 import org.apache.james.user.api.DelegationStore;
 import org.apache.james.user.api.InvalidUsernameException;
 import org.apache.james.user.api.UsersRepositoryException;
+import org.apache.james.user.api.model.UsernamePredicate;
 import org.apache.james.webadmin.Constants;
 import org.apache.james.webadmin.Routes;
 import org.apache.james.webadmin.UserCondition;
@@ -78,6 +80,7 @@ public class UserRoutes implements Routes {
     private static final String AUTHORIZED_USERS = "authorizedUsers";
     private static final String QUERY_PARAM = "query";
     private static final String ANCHOR_PARAM = "anchor";
+    private static final String DOMAIN_PARAM = "domain";
 
     private final UserService userService;
     private final JsonTransformer jsonTransformer;
@@ -179,20 +182,28 @@ public class UserRoutes implements Routes {
     }
 
     private List<UserResponse> getUsers(Request request, Response response) {
-        UserCondition combinedCondition = userConditionMap.entrySet()
+        Optional<UserCondition> combinedCondition = userConditionMap.entrySet()
             .stream()
             .filter(entry -> request.queryParams().contains(entry.getKey()))
             .map(Map.Entry::getValue)
-            .reduce(ALL, UserCondition::and);
+            .reduce(UserCondition::and);
 
         Optional<Integer> limit = ParametersExtractor.extractLimit(request).getLimit();
-        Optional<String> query = Optional.ofNullable(request.queryParams(QUERY_PARAM))
-            .filter(s -> !s.isEmpty());
+        Optional<UsernamePredicate> prefixPredicate = Optional.ofNullable(request.queryParams(QUERY_PARAM))
+            .filter(s -> !s.isEmpty())
+            .map(UsernamePredicate::prefix);
+        Optional<UsernamePredicate> domainPredicate = Optional.ofNullable(request.queryParams(DOMAIN_PARAM))
+            .filter(s -> !s.isEmpty())
+            .map(this::parseDomain)
+            .map(UsernamePredicate::domain);
+        List<UsernamePredicate> predicates = Stream.of(prefixPredicate, domainPredicate)
+            .flatMap(Optional::stream)
+            .toList();
         Optional<Username> anchor = Optional.ofNullable(request.queryParams(ANCHOR_PARAM))
             .filter(s -> !s.isEmpty())
             .map(Parsers::parseUsername);
 
-        return userService.getUsers(query, anchor, limit, combinedCondition);
+        return userService.getUsers(predicates, anchor, limit, combinedCondition);
     }
 
     private String removeUser(Request request, Response response) {
@@ -405,6 +416,19 @@ public class UserRoutes implements Routes {
         }
     }
 
+    private Domain parseDomain(String domain) {
+        try {
+            return Domain.of(domain);
+        } catch (IllegalArgumentException e) {
+            throw ErrorResponder.builder()
+                .statusCode(HttpStatus.BAD_REQUEST_400)
+                .type(ErrorType.INVALID_ARGUMENT)
+                .message("Invalid domain: " + domain)
+                .cause(e)
+                .haltError();
+        }
+    }
+
     private Username extractUsername(Request request) {
         return Parsers.parseUsername(request.params(USER_NAME));
     }
diff --git a/server/protocols/webadmin/webadmin-data/src/main/java/org/apache/james/webadmin/service/UserService.java b/server/protocols/webadmin/webadmin-data/src/main/java/org/apache/james/webadmin/service/UserService.java
index 5a798728b7..0d6b574941 100644
--- a/server/protocols/webadmin/webadmin-data/src/main/java/org/apache/james/webadmin/service/UserService.java
+++ b/server/protocols/webadmin/webadmin-data/src/main/java/org/apache/james/webadmin/service/UserService.java
@@ -19,7 +19,6 @@
 
 package org.apache.james.webadmin.service;
 
-import java.util.ArrayList;
 import java.util.List;
 import java.util.Optional;
 import java.util.function.Predicate;
@@ -30,6 +29,7 @@ import org.apache.james.core.Username;
 import org.apache.james.user.api.UsersRepository;
 import org.apache.james.user.api.UsersRepositoryException;
 import org.apache.james.user.api.model.User;
+import org.apache.james.user.api.model.UsernamePredicate;
 import org.apache.james.webadmin.dto.UserResponse;
 
 import com.google.common.collect.ImmutableList;
@@ -45,38 +45,26 @@ public class UserService {
     }
 
     /**
-     * Users sorted alphabetically, strictly after the anchor, optionally matching the query.
+     * Users matching all the predicates, sorted alphabetically, strictly after the anchor.
      *
-     * The condition is applied after the repository pagination: repository pages are read until 'limit' users
-     * matching the condition are found, or the repository is exhausted.
+     * The condition can not be applied by the repository: when supplied, users are read without limit then
+     * filtered, and the condition is only evaluated until 'limit' users matched.
      */
-    public List<UserResponse> getUsers(Optional<String> query, Optional<Username> anchor, Optional<Integer> limit, Predicate<Username> condition) {
-        List<UserResponse> result = new ArrayList<>();
-        Optional<Username> pageAnchor = anchor;
-        while (true) {
-            List<Username> page = readPage(query, pageAnchor, limit);
-            page.stream()
-                .filter(condition)
-                .limit(limit.map(value -> value - result.size()).orElse(Integer.MAX_VALUE))
-                .map(Username::asString)
-                .map(UserResponse::new)
-                .forEach(result::add);
-
-            boolean exhausted = limit.map(value -> page.size() < value).orElse(true);
-            boolean full = limit.map(value -> result.size() >= value).orElse(false);
-            if (exhausted || full) {
-                return ImmutableList.copyOf(result);
-            }
-            pageAnchor = Optional.of(page.get(page.size() - 1));
-        }
+    public List<UserResponse> getUsers(List<UsernamePredicate> predicates, Optional<Username> anchor, Optional<Integer> limit,
+                                       Optional<? extends Predicate<Username>> condition) {
+        Flux<Username> users = condition
+            .map(c -> applyLimit(Flux.from(usersRepository.searchPaginated(predicates, anchor, Optional.empty())).filter(c), limit))
+            .orElseGet(() -> Flux.from(usersRepository.searchPaginated(predicates, anchor, limit)));
+
+        return users.map(Username::asString)
+            .map(UserResponse::new)
+            .collect(ImmutableList.toImmutableList())
+            .block();
     }
 
-    private List<Username> readPage(Optional<String> query, Optional<Username> anchor, Optional<Integer> limit) {
-        return Flux.from(query
-                .map(q -> usersRepository.searchPaginated(q, anchor, limit))
-                .orElseGet(() -> usersRepository.listPaginated(anchor, limit)))
-            .collectList()
-            .block();
+    private Flux<Username> applyLimit(Flux<Username> users, Optional<Integer> limit) {
+        return limit.map(value -> users.take(value, true))
+            .orElse(users);
     }
 
     public void removeUser(Username username) throws UsersRepositoryException {
diff --git a/server/protocols/webadmin/webadmin-data/src/test/java/org/apache/james/webadmin/routes/UserRoutesTest.java b/server/protocols/webadmin/webadmin-data/src/test/java/org/apache/james/webadmin/routes/UserRoutesTest.java
index ebb10ef422..c40b5da882 100644
--- a/server/protocols/webadmin/webadmin-data/src/test/java/org/apache/james/webadmin/routes/UserRoutesTest.java
+++ b/server/protocols/webadmin/webadmin-data/src/test/java/org/apache/james/webadmin/routes/UserRoutesTest.java
@@ -26,6 +26,7 @@ import static org.apache.james.webadmin.Constants.SEPARATOR;
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.hamcrest.Matchers.is;
 import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.doThrow;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.spy;
@@ -651,7 +652,7 @@ class UserRoutesTest {
 
             @Test
             default void getShouldFailOnRepositoryException(UsersRepository usersRepository) throws Exception {
-                when(usersRepository.listPaginated(any(), any())).thenReturn(Flux.error(new UsersRepositoryException("message")));
+                doReturn(Flux.error(new UsersRepositoryException("message"))).when(usersRepository).searchPaginated(any(), any(), any());
 
                 when()
                     .get()
@@ -713,7 +714,7 @@ class UserRoutesTest {
 
             @Test
             default void getShouldFailOnUnknownException(UsersRepository usersRepository) throws Exception {
-                when(usersRepository.listPaginated(any(), any())).thenThrow(new RuntimeException());
+                doThrow(new RuntimeException()).when(usersRepository).searchPaginated(any(), any(), any());
 
                 when()
                     .get()


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org