[ 
https://issues.apache.org/jira/browse/KNOX-3585?focusedWorklogId=1055746&page=com.atlassian.jira.plugin.system.issuetabpanels:worklog-tabpanel#worklog-1055746
 ]

ASF GitHub Bot logged work on KNOX-3585:
----------------------------------------

                Author: ASF GitHub Bot
            Created on: 18/Nov/26 16:30
            Start Date: 18/Nov/26 16:30
    Worklog Time Spent: 10m 
      Work Description: smolnar82 commented on code in PR #1522:
URL: https://github.com/apache/knox/pull/1522#discussion_r4616807759


##########
gateway-server/src/main/java/org/apache/knox/gateway/services/ldap/interceptor/LDAPRolesLookupInterceptor.java:
##########
@@ -277,18 +296,125 @@ private EntryFilteringCursor 
handleSearch(SearchOperationContext ctx) throws Lda
             
ctx.setReturningAttributes(withAttributes(originalReturningAttributes, 
augmentedAttributes));
         }
 
+        int numUserAndGroupEntries = 0;
         final List<Entry> entries = new ArrayList<>();
         try (EntryFilteringCursor cursor = next(ctx)) {
             while (cursor.next()) {
+                Entry entry = cursor.get();
+                if (LdapUtils.isUserEntry(entry) || 
LdapUtils.isGroupEntry(entry)) {
+                    numUserAndGroupEntries++;
+                }
                 entries.add(cursor.get());
             }
         } catch (Exception e) {
             LOG.ldapRolesLookupFailed(LdapUtils.extractGroupName(ctx.getDn()), 
e);
             throw new LdapException(e);
         }
 
+        // Populating the roles through lookup results in one lookup request 
per entry.
+        // It is more efficient to list all the roles when the number of 
entries is large.
+        final List<Entry> resultEntries = numUserAndGroupEntries > numRoles ?

Review Comment:
   **Blocker:** `numRoles` starts at 0 and is only updated inside 
`populateRolesThroughList`, after `listRoles()` succeeds. That causes two 
problems.
   
   1. **The first search always takes the list path.** A single-user lookup has 
1 entry, which is more than 0. So instead of one `lookupRoles` call, it does a 
`listRoles()` plus a `lookupRoleAssignees()` per role.
   2. **A failing `listRoles()` makes the whole service fail permanently.** If 
it throws, the search fails with `LdapException` and `numRoles` stays 0. The 
next search with 1 or more user/group entries takes the list path again, fails 
again, and so on. Every search that works on master via per-entry lookup would 
now fail until restart, or until `listRoles()` starts succeeding.
   
   A concrete trigger for (2) on the file backend: an entry in the role-mapping 
JSON without a `roles` field. `RoleMappingEntry.getRoles()` returns null, so 
`FileBasedLdapRolesReverseLookup.listRoles()` throws a NullPointerException on 
`for (RoleAssignment roleAssignment : entry.getRoles())`. The forward lookup 
(`FileBasedLdapRolesLookup.addRoles`) tolerates that entry today. The same 
NullPointerException is in `lookupRoleAssignees` (`entry.getRoles().stream()`). 
A REST backend that doesn't implement or allow role listing, or a transient 
error, triggers (2) the same way.
   
   Suggestions:
   - If `listRoles()` fails in the list path, log it and fall back to 
`populateRolesThroughLookup(entries, ...)` instead of failing the search.
   - Don't treat "unknown" as 0. For example, start with `numRoles = -1` and 
use the lookup path while it's unknown, or prime it lazily, so a single-entry 
search never pays for the full listing.
   - Make `FileBasedLdapRolesReverseLookup.listRoles()` and 
`lookupRoleAssignees()` null-safe for `getRoles()`.
   - Add tests: `listRoles()` throws → the search still returns roles via 
lookup, and the next search still works. Plus a file-backend test with an entry 
that has no `roles`.
   



##########
gateway-server/src/main/java/org/apache/knox/gateway/services/ldap/interceptor/LDAPRolesLookupInterceptor.java:
##########
@@ -277,18 +296,125 @@ private EntryFilteringCursor 
handleSearch(SearchOperationContext ctx) throws Lda
             
ctx.setReturningAttributes(withAttributes(originalReturningAttributes, 
augmentedAttributes));
         }
 
+        int numUserAndGroupEntries = 0;
         final List<Entry> entries = new ArrayList<>();
         try (EntryFilteringCursor cursor = next(ctx)) {
             while (cursor.next()) {
+                Entry entry = cursor.get();
+                if (LdapUtils.isUserEntry(entry) || 
LdapUtils.isGroupEntry(entry)) {
+                    numUserAndGroupEntries++;
+                }
                 entries.add(cursor.get());
             }
         } catch (Exception e) {
             LOG.ldapRolesLookupFailed(LdapUtils.extractGroupName(ctx.getDn()), 
e);
             throw new LdapException(e);
         }
 
+        // Populating the roles through lookup results in one lookup request 
per entry.
+        // It is more efficient to list all the roles when the number of 
entries is large.
+        final List<Entry> resultEntries = numUserAndGroupEntries > numRoles ?
+                populateRolesThroughList(entries, augmentedAttributes) :
+                populateRolesThroughLookup(entries, augmentedAttributes);
+
+        if (!augmentedAttributes.isEmpty()) {
+            ctx.setReturningAttributes(originalReturningAttributes == null ? 
new String[0] : originalReturningAttributes);
+        }
+
+        return new EntryFilteringCursorImpl(new ListCursor<>(resultEntries), 
ctx, schemaManager);
+    }
+
+    private List<Entry> populateRolesThroughList(List<Entry> entries, 
List<String> augmentedAttributes) throws LdapException {
+        // Map of user id to the assigned roles
+        final Map<String, List<String>> userRoleAssignments = new HashMap<>();
+        // Map of group id to the assigned roles
+        final Map<String, List<String>> groupRoleAssignments = new HashMap<>();
+        try {
+            Collection<String> rolesList = rolesLookupService.listRoles();
+            numRoles = rolesList.size();
+            for (String roleName : rolesList) {
+                try {
+                    RoleAssignees assignees = 
rolesLookupService.lookupRoleAssignees(roleName);
+                    if (assignees != null) {
+                        if (assignees.getUsers() != null && 
!assignees.getUsers().isEmpty()) {
+                            for (String userName : assignees.getUsers()) {
+                                if 
(!userRoleAssignments.containsKey(userName)) {
+                                    ArrayList<String> roles = new 
ArrayList<>();
+                                    roles.add(roleName);
+                                    userRoleAssignments.put(userName, roles);
+                                } else {
+                                    
userRoleAssignments.get(userName).add(roleName);
+                                }
+
+                            }
+                        }
+                        if (assignees.getGroups() != null && 
!assignees.getGroups().isEmpty()) {
+                            for (String groupName : assignees.getGroups()) {
+                                if 
(!groupRoleAssignments.containsKey(groupName)) {
+                                    ArrayList<String> roles = new 
ArrayList<>();
+                                    roles.add(roleName);
+                                    groupRoleAssignments.put(groupName, roles);
+                                } else {
+                                    
groupRoleAssignments.get(groupName).add(roleName);
+                                }
+                            }
+                        }
+                    }
+                } catch (Exception e) {
+                    LOG.ldapRolesReverseLookupFailed(roleName, e);

Review Comment:
   **Should fix before merge, or confirm it's intended:** a failure of 
`lookupRoleAssignees(roleName)` for a single role is logged and swallowed here, 
and the search carries on. Every user/group assigned that role then comes back 
without it, and the client has no indication anything is wrong. The only trace 
is the ERROR in the gateway log.
   
   That's inconsistent with the lookup path. In `populateRolesThroughLookup`, a 
failure in `lookupRoles` fails the search with `LdapException`. So whether a 
client gets an error or a silently incomplete role set now depends on how many 
entries the search happened to return. For a roles/authorization source I'd 
rather fail loudly than return partial data. One transient REST error for a 
single role shouldn't quietly strip that role from every user in the result.
   
   Suggestion: either rethrow, which fails the search just like the lookup 
path, or abandon the list strategy for this search and fall back to 
`populateRolesThroughLookup(entries, ...)`. The fallback fits well with the 
fallback suggested on the `numRoles` comment. A test where 
`lookupRoleAssignees` throws for one role would pin down the behavior.
   



##########
gateway-server/src/main/java/org/apache/knox/gateway/services/ldap/interceptor/LDAPRolesLookupInterceptor.java:
##########
@@ -277,18 +296,125 @@ private EntryFilteringCursor 
handleSearch(SearchOperationContext ctx) throws Lda
             
ctx.setReturningAttributes(withAttributes(originalReturningAttributes, 
augmentedAttributes));
         }
 
+        int numUserAndGroupEntries = 0;
         final List<Entry> entries = new ArrayList<>();
         try (EntryFilteringCursor cursor = next(ctx)) {
             while (cursor.next()) {
+                Entry entry = cursor.get();
+                if (LdapUtils.isUserEntry(entry) || 
LdapUtils.isGroupEntry(entry)) {
+                    numUserAndGroupEntries++;
+                }
                 entries.add(cursor.get());
             }
         } catch (Exception e) {
             LOG.ldapRolesLookupFailed(LdapUtils.extractGroupName(ctx.getDn()), 
e);
             throw new LdapException(e);
         }
 
+        // Populating the roles through lookup results in one lookup request 
per entry.
+        // It is more efficient to list all the roles when the number of 
entries is large.
+        final List<Entry> resultEntries = numUserAndGroupEntries > numRoles ?
+                populateRolesThroughList(entries, augmentedAttributes) :
+                populateRolesThroughLookup(entries, augmentedAttributes);
+
+        if (!augmentedAttributes.isEmpty()) {
+            ctx.setReturningAttributes(originalReturningAttributes == null ? 
new String[0] : originalReturningAttributes);
+        }
+
+        return new EntryFilteringCursorImpl(new ListCursor<>(resultEntries), 
ctx, schemaManager);
+    }
+
+    private List<Entry> populateRolesThroughList(List<Entry> entries, 
List<String> augmentedAttributes) throws LdapException {
+        // Map of user id to the assigned roles
+        final Map<String, List<String>> userRoleAssignments = new HashMap<>();
+        // Map of group id to the assigned roles
+        final Map<String, List<String>> groupRoleAssignments = new HashMap<>();
+        try {
+            Collection<String> rolesList = rolesLookupService.listRoles();
+            numRoles = rolesList.size();
+            for (String roleName : rolesList) {
+                try {
+                    RoleAssignees assignees = 
rolesLookupService.lookupRoleAssignees(roleName);
+                    if (assignees != null) {
+                        if (assignees.getUsers() != null && 
!assignees.getUsers().isEmpty()) {
+                            for (String userName : assignees.getUsers()) {
+                                if 
(!userRoleAssignments.containsKey(userName)) {
+                                    ArrayList<String> roles = new 
ArrayList<>();
+                                    roles.add(roleName);
+                                    userRoleAssignments.put(userName, roles);
+                                } else {
+                                    
userRoleAssignments.get(userName).add(roleName);
+                                }
+
+                            }
+                        }
+                        if (assignees.getGroups() != null && 
!assignees.getGroups().isEmpty()) {
+                            for (String groupName : assignees.getGroups()) {
+                                if 
(!groupRoleAssignments.containsKey(groupName)) {
+                                    ArrayList<String> roles = new 
ArrayList<>();
+                                    roles.add(roleName);
+                                    groupRoleAssignments.put(groupName, roles);
+                                } else {
+                                    
groupRoleAssignments.get(groupName).add(roleName);
+                                }
+                            }
+                        }
+                    }
+                } catch (Exception e) {
+                    LOG.ldapRolesReverseLookupFailed(roleName, e);
+                }
+            }
+        } catch (Exception e) {
+            LOG.ldapRolesListFailed(e);
+            throw new LdapException(e);
+        }
+
+        final List<Entry> roleEntries = new ArrayList<>();
+        final List<Entry> resultEntries = new ArrayList<>(entries.size());
+
+        for (Entry entry : entries) {
+            try {
+                if (LdapUtils.isGroupEntry(entry)) {
+                    roleEntries.addAll(translateGroupEntry(entry, 
groupRoleAssignments));
+                } else {
+                    final String username = 
toRolesLookupId(LdapUtils.extractUsernameFromEntry(entry, "uid", "cn"));
+                    final List<String> roles = new ArrayList<>();
+                    if (userRoleAssignments.containsKey(username)) {
+                        roles.addAll(userRoleAssignments.get(username));
+                    }
+                    Attribute memberOfAttribute = entry.get("memberOf");
+                    if (memberOfAttribute != null) {
+                        for (Value groupDnValue : memberOfAttribute) {
+                            // Key on the same id the lookup branch sends to 
the backend (toRolesLookupId),
+                            // so a case-sensitive roles backend is matched 
consistently across both branches.
+                            String groupName = 
toRolesLookupId(LdapUtils.extractGroupName(new Dn(groupDnValue.getString())));

Review Comment:
   **Non-blocking:** in the list path, a single malformed `memberOf` value 
makes `new Dn(...)` throw `LdapInvalidDnException`. The surrounding catch then 
fails the whole search with `LdapException`. The lookup path doesn't do this: 
`fetchGroups(entry)` ignores invalid DNs and skips that value. So the same 
entry can succeed or fail depending on which strategy was picked.
   
   `fetchGroups` already does exactly what this loop needs: parse, 
`extractGroupName`, `toRolesLookupId`, skip invalid. So this block can simply 
be:
   
   ```java
   for (String groupName : fetchGroups(entry)) {
       final List<String> groupRoles = groupRoleAssignments.get(groupName);
       if (groupRoles != null) {
           roles.addAll(groupRoles);
       }
   }
   ```
   
   That keeps both paths consistent, and removes the duplicated `memberOf` 
parsing.
   



##########
gateway-server/src/main/java/org/apache/knox/gateway/services/ldap/interceptor/LDAPRolesLookupInterceptor.java:
##########
@@ -277,18 +296,125 @@ private EntryFilteringCursor 
handleSearch(SearchOperationContext ctx) throws Lda
             
ctx.setReturningAttributes(withAttributes(originalReturningAttributes, 
augmentedAttributes));
         }
 
+        int numUserAndGroupEntries = 0;
         final List<Entry> entries = new ArrayList<>();
         try (EntryFilteringCursor cursor = next(ctx)) {
             while (cursor.next()) {
+                Entry entry = cursor.get();
+                if (LdapUtils.isUserEntry(entry) || 
LdapUtils.isGroupEntry(entry)) {
+                    numUserAndGroupEntries++;
+                }
                 entries.add(cursor.get());
             }
         } catch (Exception e) {
             LOG.ldapRolesLookupFailed(LdapUtils.extractGroupName(ctx.getDn()), 
e);
             throw new LdapException(e);
         }
 
+        // Populating the roles through lookup results in one lookup request 
per entry.
+        // It is more efficient to list all the roles when the number of 
entries is large.

Review Comment:
   **Non-blocking / follow-up:** the threshold `numUserAndGroupEntries > 
numRoles` assumes the list strategy costs about `numRoles` requests. On the 
REST backend it costs more than that:
   
   - `listRoles()`: 1 list request.
   - `RestApiLdapRolesReverseLookup.lookupRoleAssignees(role)`, per role: a 
filtered `listRoles(roleAssignment)` to resolve the role id, plus 
`getMembers(roleId)`. That's 2 requests per role.
   
   So the list path is about `2 * numRoles + 1` requests, all serial, inside 
the LDAP search. The lookup path is 1 request per entry. With `numRoles < 
entries < 2 * numRoles + 1`, the "optimized" path makes more remote calls than 
the one it replaces. For example, with 50 roles and 60 entries: 101 requests 
instead of 60.
   
   On the file backend, every `lookupRoleAssignees` call also re-reads and 
re-parses the mapping file, so the list path parses the file `numRoles + 1` 
times.
   
   Options, any of which could be a follow-up:
   - Make the threshold reflect the real cost. At minimum `entries > 2 * 
numRoles + 1` for REST, or better, let the `LDAPRolesLookupService` expose an 
estimated per-role cost or the comparison itself.
   - In the list path, reuse the role ids from the initial `listRoles()` call 
instead of re-listing per role. That brings it down to `numRoles + 1`.
   - Longer term, a bulk "all role assignments" call, or caching the 
role→assignees map for a short TTL.
   





Issue Time Tracking
-------------------

    Worklog Id:     (was: 1055746)
    Time Spent: 40m  (was: 0.5h)

> Optimize roles lookup for large result sets
> -------------------------------------------
>
>                 Key: KNOX-3585
>                 URL: https://issues.apache.org/jira/browse/KNOX-3585
>             Project: Apache Knox
>          Issue Type: Improvement
>          Components: LDAP
>    Affects Versions: 3.0.0
>            Reporter: David Han
>            Assignee: David Han
>            Priority: Major
>             Fix For: 3.1.0
>
>          Time Spent: 40m
>  Remaining Estimate: 0h
>
> The roles lookup interceptor makes a lookup call for each user entry. If the 
> entry set is large, this may result in 1000s of calls to the roles lookup 
> server before the results are returned.
> If the number of results are greater than the number of roles, it would be 
> faster to retrieve all roles from the role server and perform the mapping in 
> the roles lookup interceptor.



--
This message was sent by Atlassian Jira
(v10.3.26#10030026)

Reply via email to