Copilot commented on code in PR #1401:
URL: https://github.com/apache/ranger/pull/1401#discussion_r4813590133


##########
security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyAdminImpl.java:
##########
@@ -848,17 +868,79 @@ private Set<String> 
getAllModifiedAccessTypes(RangerPolicy oldPolicy, RangerPoli
         ret.addAll(getAccessTypesDiff(newGroupAccesses, oldGroupAccesses));
         ret.addAll(getAccessTypesDiff(newRoleAccesses, oldRoleAccesses));
 
-        if (ret.isEmpty()) {
-            // Empty access-type delta (delete, or updates that do not 
add/remove grants) must be authorized against
-            // every access-type in the stored policy, not a generic _admin 
token.
-            ret.addAll(getAllAccessTypes(oldPolicy, serviceDef));
+        return ret;
+    }
+
+    /**
+     * Access types for which a principal's grant option (delegateAdmin) was 
added or removed. Such a change modifies
+     * only these access types, so authorizing it must not require authority 
over the policy's other access types
+     * (e.g. revoking the grant option on select from a principal that also 
holds update with grant option).
+     */
+    private Set<String> getDelegatedAccessTypesDiff(RangerPolicy oldPolicy, 
RangerPolicy policy, RangerServiceDef serviceDef) {
+        return getModifiedAccessTypes(getDelegatedItemsView(oldPolicy), 
getDelegatedItemsView(policy), serviceDef);
+    }
+
+    /**
+     * True if nothing but grant options changed: the same access-types are 
granted to the same principals under the
+     * same item-types, conditions and item-info, and the grant option of some 
access-types was added or removed.
+     * Any other change, for example to the condition of an unrelated item, 
makes this false so that it is still
+     * authorized against the access-types it modifies (or the whole policy, 
if it modifies none).
+     */
+    private boolean isGrantOptionOnlyChange(RangerPolicy oldPolicy, 
RangerPolicy policy, RangerServiceDef serviceDef) {
+        return getModifiedAccessTypes(oldPolicy, policy, serviceDef).isEmpty() 
&& !getDelegatedAccessTypesDiff(oldPolicy, policy, serviceDef).isEmpty();

Review Comment:
   A caller delegated only SELECT can toggle Bob's SELECT grant option and add 
a valid, empty-access `delegateAdmin=true` item for Eve, even when the policy 
also contains UPDATE. The empty-access item contributes nothing to either diff, 
so this is classified as grant-option-only and bypasses the full-policy 
authorization required for the new delegated administrator. Treat changes to 
delegate-admin-only items as scope changes rather than excluding them from 
authorization.



##########
security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyAdminImpl.java:
##########
@@ -1019,15 +1101,35 @@ private <K> Set<String> getAccessTypesDiff(Map<K, 
Set<String>> newAccessesMap, M
     }
 
     private boolean isPolicyScopeChanged(RangerPolicy oldPolicy, RangerPolicy 
policy) {
+        return isPolicyScopeFieldsChanged(oldPolicy, policy) || 
isDelegateAdminPrincipalsChanged(oldPolicy, policy);
+    }
+
+    /**
+     * Same as {@link #isPolicyScopeChanged(RangerPolicy, RangerPolicy)}, 
except that a principal gaining its first or
+     * losing its last grant option is not a scope change when nothing but 
grant options changed: that is a change of
+     * the access types whose grant option changed only (see 
getAllModifiedAccessTypes).
+     */
+    private boolean isPolicyScopeChanged(RangerPolicy oldPolicy, RangerPolicy 
policy, RangerServiceDef serviceDef) {
+        return isPolicyScopeFieldsChanged(oldPolicy, policy) || 
(isDelegateAdminPrincipalsChanged(oldPolicy, policy) && 
!isGrantOptionOnlyChange(oldPolicy, policy, serviceDef));

Review Comment:
   If Bob holds SELECT without grant option and Alice has delegation authority 
only for UPDATE, granting Bob UPDATE WITH GRANT OPTION passes the initial 
authorization but fails `ensureAdminAccess()`. Adding both a new access and 
Bob's first grant option makes `isGrantOptionOnlyChange()` false, so this check 
unnecessarily requires SELECT authority too. Authorize combined 
access/grant-option additions against their changed access types while 
retaining full-policy checks for genuine scope changes.



##########
security-admin/src/main/java/org/apache/ranger/rest/ServiceRESTUtil.java:
##########
@@ -467,731 +374,677 @@ private static void combinePolicyItems(RangerPolicy 
existingPolicy, RangerPolicy
         }
     }
 
-    private static void processApplyPolicyForItemType(RangerPolicy 
existingPolicy, RangerPolicy appliedPolicy, PolicyTermType policyItemType) {
-        LOG.debug("==> ServiceRESTUtil.processApplyPolicyForItemType()");
+    private static void compactPolicy(RangerPolicy policy) {
+        policy.setPolicyItems(mergePolicyItems(policy.getPolicyItems()));
+        
policy.setDenyPolicyItems(mergePolicyItems(policy.getDenyPolicyItems()));
+        
policy.setAllowExceptions(mergePolicyItems(policy.getAllowExceptions()));
+        policy.setDenyExceptions(mergePolicyItems(policy.getDenyExceptions()));
+    }
+
+    private static List<RangerPolicyItem> 
mergePolicyItems(List<RangerPolicyItem> policyItems) {
+        List<RangerPolicyItem> ret = new ArrayList<>();
 
-        List<RangerPolicyItem> appliedPolicyItems = null;
+        if (CollectionUtils.isNotEmpty(policyItems)) {
+            Map<String, RangerPolicyItem> matchedPolicyItems = new HashMap<>();
 
-        switch (policyItemType) {
-            case ALLOW:
-                appliedPolicyItems = appliedPolicy.getPolicyItems();
-                break;
-            case DENY:
-                appliedPolicyItems = appliedPolicy.getDenyPolicyItems();
-                break;
-            case ALLOW_EXCEPTIONS:
-                appliedPolicyItems = appliedPolicy.getAllowExceptions();
-                break;
-            case DENY_EXCEPTIONS:
-                appliedPolicyItems = appliedPolicy.getDenyExceptions();
-                break;
-            default:
-                LOG.warn("processApplyPolicyForItemType(): invalid 
policyItemType={}", policyItemType);
-        }
+            for (RangerPolicyItem policyItem : policyItems) {
+                if ((CollectionUtils.isEmpty(policyItem.getUsers()) && 
CollectionUtils.isEmpty(policyItem.getGroups()) && 
CollectionUtils.isEmpty(policyItem.getRoles())) ||
+                        (CollectionUtils.isEmpty(policyItem.getAccesses()) && 
!policyItem.getDelegateAdmin())) {
+                    continue;
+                }
 
-        if (CollectionUtils.isNotEmpty(appliedPolicyItems)) {
-            Set<String> users  = new HashSet<>();
-            Set<String> groups = new HashSet<>();
-            Set<String> roles  = new HashSet<>();
+                if (CollectionUtils.isNotEmpty(policyItem.getConditions())) {
+                    ret.add(policyItem);
+                    continue;
+                }
 
-            Map<String, RangerPolicyItem[]> userPolicyItems  = new HashMap<>();
-            Map<String, RangerPolicyItem[]> groupPolicyItems = new HashMap<>();
-            Map<String, RangerPolicyItem[]> rolePolicyItems  = new HashMap<>();
+                TreeSet<String> accesses = new TreeSet<>();
 
-            // Extract users, groups, and roles specified in appliedPolicy 
items
-            extractUsersGroupsAndRoles(appliedPolicyItems, users, groups, 
roles);
+                for (RangerPolicyItemAccess access : policyItem.getAccesses()) 
{
+                    accesses.add(access.getType());
+                }
 
-            // Split existing policyItems for users, groups, and roles 
extracted from appliedPolicyItem into userPolicyItems, groupPolicyItems, and 
rolePolicyItems
-            splitExistingPolicyItems(existingPolicy, users, userPolicyItems, 
groups, groupPolicyItems, roles, rolePolicyItems);
+                if (policyItem.getDelegateAdmin()) {
+                    accesses.add("delegateAdmin");
+                }
 
-            // Apply policyItems of given type in appliedPolicy to policyItems 
extracted from existingPolicy
-            applyPolicyItems(appliedPolicyItems, policyItemType, 
userPolicyItems, groupPolicyItems, rolePolicyItems);
+                String           allAccessesString  = accesses.toString();
+                RangerPolicyItem matchingPolicyItem = 
matchedPolicyItems.get(allAccessesString);
 
-            // Add modified/new policyItems back to existing policy
-            mergeProcessedPolicyItems(existingPolicy, userPolicyItems, 
groupPolicyItems, rolePolicyItems);
+                if (matchingPolicyItem != null) {
+                    addDistinctUsers(policyItem.getUsers(), 
matchingPolicyItem);
+                    addDistinctGroups(policyItem.getGroups(), 
matchingPolicyItem);
+                    addDistinctRoles(policyItem.getRoles(), 
matchingPolicyItem);
+                } else {
+                    matchedPolicyItems.put(allAccessesString, policyItem);
+                }
+            }
 
-            compactPolicy(existingPolicy);
+            for (Map.Entry<String, RangerPolicyItem> entry : 
matchedPolicyItems.entrySet()) {
+                ret.add(entry.getValue());
+            }
         }
 
-        LOG.debug("<== ServiceRESTUtil.processApplyPolicyForItemType()");
+        return ret;
     }
 
-    private static void mergeExactMatchPolicyForItemType(RangerPolicy 
existingPolicy, RangerPolicy appliedPolicy, PolicyTermType policyItemType) {
-        LOG.debug("==> ServiceRESTUtil.mergeExactMatchPolicyForItemType()");
-        List<RangerPolicyItem> appliedPolicyItems = null;
+    private static void addDistinctUsers(List<String> users, RangerPolicyItem 
policyItem) {
+        for (String user : users) {
+            if (!policyItem.getUsers().contains(user)) {
+                policyItem.addUser(user);
+            }
+        }
+    }
 
-        switch (policyItemType) {
-            case ALLOW:
-                appliedPolicyItems = appliedPolicy.getPolicyItems();
-                break;
-            case DENY:
-                appliedPolicyItems = appliedPolicy.getDenyPolicyItems();
-                break;
-            case ALLOW_EXCEPTIONS:
-                appliedPolicyItems = appliedPolicy.getAllowExceptions();
-                break;
-            case DENY_EXCEPTIONS:
-                appliedPolicyItems = appliedPolicy.getDenyExceptions();
-                break;
-            default:
-                LOG.warn("mergeExactMatchPolicyForItemType(): invalid 
policyItemType={}", policyItemType);
+    private static void addDistinctGroups(List<String> groups, 
RangerPolicyItem policyItem) {
+        for (String group : groups) {
+            if (!policyItem.getGroups().contains(group)) {
+                policyItem.addGroup(group);
+            }
         }
+    }
 
-        if (CollectionUtils.isNotEmpty(appliedPolicyItems)) {
-            Set<String> users  = new HashSet<>();
-            Set<String> groups = new HashSet<>();
-            Set<String> roles  = new HashSet<>();
+    private static void addDistinctRoles(List<String> roles, RangerPolicyItem 
policyItem) {
+        for (String role : roles) {
+            if (!policyItem.getRoles().contains(role)) {
+                policyItem.addRole(role);
+            }
+        }
+    }
 
-            Map<String, RangerPolicyItem[]> userPolicyItems  = new HashMap<>();
-            Map<String, RangerPolicyItem[]> groupPolicyItems = new HashMap<>();
-            Map<String, RangerPolicyItem[]> rolePolicyItems  = new HashMap<>();
+    private static boolean removeUsersGroupsAndRolesFromPolicy(RangerPolicy 
policy, Set<String> users, Set<String> groups, Set<String> roles) {
+        boolean                policyUpdated = false;
+        List<RangerPolicyItem> policyItems   = policy.getPolicyItems();
+        int                    numOfItems    = policyItems.size();
 
-            // Extract users and groups specified in appliedPolicy items
-            extractUsersGroupsAndRoles(appliedPolicyItems, users, groups, 
roles);
+        for (int i = 0; i < numOfItems; i++) {
+            RangerPolicyItem policyItem = policyItems.get(i);
 
-            // Split existing policyItems for users and groups extracted from 
appliedPolicyItem into userPolicyItems and groupPolicyItems
-            splitExistingPolicyItems(existingPolicy, users, userPolicyItems, 
groups, groupPolicyItems, roles, rolePolicyItems);
+            if (CollectionUtils.containsAny(policyItem.getUsers(), users)) {
+                policyItem.getUsers().removeAll(users);
 
-            // Apply policyItems of given type in appliedPlicy to policyItems 
extracted from existingPolicy
-            mergePolicyItems(appliedPolicyItems, policyItemType, 
userPolicyItems, groupPolicyItems, rolePolicyItems);
+                policyUpdated = true;
+            }
 
-            // Add modified/new policyItems back to existing policy
-            mergeProcessedPolicyItems(existingPolicy, userPolicyItems, 
groupPolicyItems, rolePolicyItems);
+            if (CollectionUtils.containsAny(policyItem.getGroups(), groups)) {
+                policyItem.getGroups().removeAll(groups);
 
-            compactPolicy(existingPolicy);
-        }
+                policyUpdated = true;
+            }
 
-        LOG.debug("<== ServiceRESTUtil.mergeExactMatchPolicyForItemType()");
-    }
+            if (CollectionUtils.containsAny(policyItem.getRoles(), roles)) {
+                policyItem.getRoles().removeAll(roles);
 
-    private static void extractUsersGroupsAndRoles(List<RangerPolicyItem> 
policyItems, Set<String> users, Set<String> groups, Set<String> roles) {
-        LOG.debug("==> ServiceRESTUtil.extractUsersGroupsAndRoles()");
+                policyUpdated = true;
+            }
 
-        if (CollectionUtils.isNotEmpty(policyItems)) {
-            for (RangerPolicyItem policyItem : policyItems) {
-                if (CollectionUtils.isNotEmpty(policyItem.getUsers())) {
-                    users.addAll(policyItem.getUsers());
-                }
+            if (CollectionUtils.isEmpty(policyItem.getUsers()) && 
CollectionUtils.isEmpty(policyItem.getGroups()) && 
CollectionUtils.isEmpty(policyItem.getRoles())) {
+                policyItems.remove(i);
 
-                if (CollectionUtils.isNotEmpty(policyItem.getGroups())) {
-                    groups.addAll(policyItem.getGroups());
-                }
+                numOfItems--;
+                i--;
 
-                if (CollectionUtils.isNotEmpty(policyItem.getRoles())) {
-                    roles.addAll(policyItem.getRoles());
-                }
+                policyUpdated = true;
             }
         }
 
-        LOG.debug("<== ServiceRESTUtil.extractUsersGroupsAndRoles()");
+        return policyUpdated;
     }
 
-    private static void splitExistingPolicyItems(RangerPolicy existingPolicy, 
Set<String> users, Map<String, RangerPolicyItem[]> userPolicyItems, Set<String> 
groups, Map<String, RangerPolicyItem[]> groupPolicyItems, Set<String> roles, 
Map<String, RangerPolicyItem[]> rolePolicyItems) {
-        if (existingPolicy == null || users == null || userPolicyItems == null 
|| groups == null || groupPolicyItems == null || roles == null || 
rolePolicyItems == null) {
-            return;
-        }
-
-        LOG.debug("==> ServiceRESTUtil.splitExistingPolicyItems()");
+    /**
+     * Returns the effective permissions of the policy as a set of (term, 
principal, accessType, delegateAdmin, conditions)
+     * entries; independent of how principals are grouped into policy items 
and compared by effective permission rather
+     * than by stored access name: an access type that implies others (Hive's 
all) stands for the access types it implies, and the grant
+     * option of an access type is combined (logical or) over all items of the 
same term, principal and conditions.
+     * An access type that is held both through "all" and individually is 
therefore a single permission.
+     */
+    static Set<String> getPermissionSet(RangerPolicy policy, Map<String, 
Set<String>> impliedGrants) {
+        Map<String, Boolean> permissions = new HashMap<>();
 
-        List<RangerPolicyItem> allowItems          = 
existingPolicy.getPolicyItems();
-        List<RangerPolicyItem> denyItems           = 
existingPolicy.getDenyPolicyItems();
-        List<RangerPolicyItem> allowExceptionItems = 
existingPolicy.getAllowExceptions();
-        List<RangerPolicyItem> denyExceptionItems  = 
existingPolicy.getDenyExceptions();
+        addPermissions(permissions, PolicyTermType.ALLOW, 
policy.getPolicyItems(), impliedGrants);
+        addPermissions(permissions, PolicyTermType.DENY, 
policy.getDenyPolicyItems(), impliedGrants);
+        addPermissions(permissions, PolicyTermType.ALLOW_EXCEPTIONS, 
policy.getAllowExceptions(), impliedGrants);
+        addPermissions(permissions, PolicyTermType.DENY_EXCEPTIONS, 
policy.getDenyExceptions(), impliedGrants);
 
-        for (String user : users) {
-            RangerPolicyItem[] value = userPolicyItems.computeIfAbsent(user, k 
-> new RangerPolicyItem[4]);
-            RangerPolicyItem   policyItem;
-
-            policyItem                                       = 
splitAndGetConsolidatedPolicyItemForUser(allowItems, user);
-            value[PolicyTermType.ALLOW.ordinal()]            = policyItem;
-            policyItem                                       = 
splitAndGetConsolidatedPolicyItemForUser(denyItems, user);
-            value[PolicyTermType.DENY.ordinal()]             = policyItem;
-            policyItem                                       = 
splitAndGetConsolidatedPolicyItemForUser(allowExceptionItems, user);
-            value[PolicyTermType.ALLOW_EXCEPTIONS.ordinal()] = policyItem;
-            policyItem                                       = 
splitAndGetConsolidatedPolicyItemForUser(denyExceptionItems, user);
-            value[PolicyTermType.DENY_EXCEPTIONS.ordinal()]  = policyItem;
-        }
+        Set<String> ret = new HashSet<>();
 
-        for (String group : groups) {
-            RangerPolicyItem[] value = groupPolicyItems.computeIfAbsent(group, 
k -> new RangerPolicyItem[4]);
-            RangerPolicyItem   policyItem;
-
-            policyItem                                       = 
splitAndGetConsolidatedPolicyItemForGroup(allowItems, group);
-            value[PolicyTermType.ALLOW.ordinal()]            = policyItem;
-            policyItem                                       = 
splitAndGetConsolidatedPolicyItemForGroup(denyItems, group);
-            value[PolicyTermType.DENY.ordinal()]             = policyItem;
-            policyItem                                       = 
splitAndGetConsolidatedPolicyItemForGroup(allowExceptionItems, group);
-            value[PolicyTermType.ALLOW_EXCEPTIONS.ordinal()] = policyItem;
-            policyItem                                       = 
splitAndGetConsolidatedPolicyItemForGroup(denyExceptionItems, group);
-            value[PolicyTermType.DENY_EXCEPTIONS.ordinal()]  = policyItem;
-        }
-        for (String role : roles) {
-            RangerPolicyItem[] value = rolePolicyItems.computeIfAbsent(role, k 
-> new RangerPolicyItem[4]);
-            RangerPolicyItem   policyItem;
-
-            policyItem                                       = 
splitAndGetConsolidatedPolicyItemForRole(allowItems, role);
-            value[PolicyTermType.ALLOW.ordinal()]            = policyItem;
-            policyItem                                       = 
splitAndGetConsolidatedPolicyItemForRole(denyItems, role);
-            value[PolicyTermType.DENY.ordinal()]             = policyItem;
-            policyItem                                       = 
splitAndGetConsolidatedPolicyItemForRole(allowExceptionItems, role);
-            value[PolicyTermType.ALLOW_EXCEPTIONS.ordinal()] = policyItem;
-            policyItem                                       = 
splitAndGetConsolidatedPolicyItemForRole(denyExceptionItems, role);
-            value[PolicyTermType.DENY_EXCEPTIONS.ordinal()]  = policyItem;
+        for (Map.Entry<String, Boolean> entry : permissions.entrySet()) {
+            ret.add(entry.getKey() + "|delegateAdmin=" + entry.getValue());
         }
 
-        LOG.debug("<== ServiceRESTUtil.splitExistingPolicyItems()");
+        return ret;
     }
 
-    private static RangerPolicyItem 
splitAndGetConsolidatedPolicyItemForUser(List<RangerPolicyItem> policyItems, 
String user) {
-        LOG.debug("==> 
ServiceRESTUtil.splitAndGetConsolidatedPolicyItemForUser()");
+    private static void addPermissions(Map<String, Boolean> permissions, 
PolicyTermType termType, List<RangerPolicyItem> policyItems, Map<String, 
Set<String>> impliedGrants) {
+        for (RangerPolicyItem policyItem : policyItems) {
+            Set<String> accessTypes = new TreeSet<>();
 
-        RangerPolicyItem ret = null;
+            for (String accessType : getAllowedAccessTypes(policyItem)) {
+                Set<String> implied = impliedGrants.get(accessType);
 
-        if (CollectionUtils.isNotEmpty(policyItems)) {
-            for (RangerPolicyItem policyItem : policyItems) {
-                List<String> users = policyItem.getUsers();
+                if (implied != null) {
+                    accessTypes.addAll(implied);
+                } else {
+                    accessTypes.add(accessType);
+                }
+            }
 
-                if (users.contains(user)) {
-                    if (ret == null) {
-                        ret = new RangerPolicyItem();
-                    }
+            if (accessTypes.isEmpty() && policyItem.getDelegateAdmin()) {
+                accessTypes = Collections.singleton("");
+            }
 
-                    ret.addUser(user);
+            String suffix = "|conditions=" + policyItem.getConditions();
 
-                    if (policyItem.getDelegateAdmin()) {
-                        ret.setDelegateAdmin(Boolean.TRUE);
+            for (PrincipalType principalType : PrincipalType.values()) {
+                for (String principal : 
principalType.getPrincipals(policyItem)) {
+                    for (String accessType : accessTypes) {
+                        permissions.merge(termType + "|" + principalType + "|" 
+ principal + "|" + accessType + suffix, policyItem.getDelegateAdmin(), 
Boolean::logicalOr);
                     }
-
-                    addAccesses(ret, policyItem.getAccesses());
-
-                    // Remove this user from existingPolicyItem
-                    users.remove(user);
                 }
             }
         }
-
-        LOG.debug("<== 
ServiceRESTUtil.splitAndGetConsolidatedPolicyItemForUser()");
-
-        return ret;
     }
 
-    private static RangerPolicyItem 
splitAndGetConsolidatedPolicyItemForGroup(List<RangerPolicyItem> policyItems, 
String group) {
-        LOG.debug("==> 
ServiceRESTUtil.splitAndGetConsolidatedPolicyItemForGroup()");
-
-        RangerPolicyItem ret = null;
+    private static void grantToPrincipal(RangerPolicy policy, PrincipalType 
principalType, String principal, Set<String> accessTypes, boolean 
delegateAdmin, Map<String, Set<String>> impliedGrants) {
+        applyToPrincipal(policy, PolicyTermType.ALLOW, principalType, 
principal, accessTypes, delegateAdmin, true, impliedGrants);
+    }
 
-        if (CollectionUtils.isNotEmpty(policyItems)) {
-            for (RangerPolicyItem policyItem : policyItems) {
-                List<String> groups = policyItem.getGroups();
+    /**
+     * Applies the given policy items of the given term type to the existing 
policy, principal by principal.
+     *
+     * @param enforceTermInterplay when true, applying an allow overrides the 
principal's deny (and vice versa) as done by applyPolicy;
+     *                             when false, items are only merged in 
(policy import)
+     */
+    private static void applyPolicyItems(RangerPolicy existingPolicy, 
RangerPolicy appliedPolicy, PolicyTermType termType, boolean 
enforceTermInterplay) {
+        List<RangerPolicyItem> appliedPolicyItems = 
getPolicyItems(appliedPolicy, termType);
 
-                if (groups.contains(group)) {
-                    if (ret == null) {
-                        ret = new RangerPolicyItem();
-                    }
+        if (CollectionUtils.isNotEmpty(appliedPolicyItems)) {
+            for (RangerPolicyItem appliedPolicyItem : appliedPolicyItems) {
+                Set<String> accessTypes   = new TreeSet<>();
+                boolean     delegateAdmin = 
Boolean.TRUE.equals(appliedPolicyItem.getDelegateAdmin());
 
-                    ret.addGroup(group);
+                for (RangerPolicyItemAccess access : 
appliedPolicyItem.getAccesses()) {
+                    accessTypes.add(access.getType());
+                }
 
-                    if (policyItem.getDelegateAdmin()) {
-                        ret.setDelegateAdmin(Boolean.TRUE);
+                for (PrincipalType principalType : PrincipalType.values()) {
+                    for (String principal : new 
ArrayList<>(principalType.getPrincipals(appliedPolicyItem))) {
+                        applyToPrincipal(existingPolicy, termType, 
principalType, principal, accessTypes, delegateAdmin, enforceTermInterplay, 
Collections.emptyMap());
                     }
-
-                    addAccesses(ret, policyItem.getAccesses());
-
-                    // Remove this group from existingPolicyItem
-                    groups.remove(group);
                 }
             }
-        }
-
-        LOG.debug("<== 
ServiceRESTUtil.splitAndGetConsolidatedPolicyItemForGroup()");
 
-        return ret;
+            compactPolicy(existingPolicy);
+        }
     }
 
-    private static RangerPolicyItem 
splitAndGetConsolidatedPolicyItemForRole(List<RangerPolicyItem> policyItems, 
String role) {
-        LOG.debug("==> 
ServiceRESTUtil.splitAndGetConsolidatedPolicyItemForGroup()");
+    private static void applyToPrincipal(RangerPolicy policy, PolicyTermType 
termType, PrincipalType principalType, String principal, Set<String> 
accessTypes, boolean delegateAdmin, boolean enforceTermInterplay, Map<String, 
Set<String>> impliedGrants) {
+        mergeIntoPrincipal(policy, termType, principalType, principal, 
accessTypes, delegateAdmin, impliedGrants);
 
-        RangerPolicyItem ret = null;
+        if (enforceTermInterplay) {
+            switch (termType) {
+                case ALLOW:
+                    // allowed accesses override the principal's own deny and 
allow-exception entries
+                    if 
(removeAccessesFromPrincipal(policy.getDenyPolicyItems(), 
policy::addDenyPolicyItem, principalType, principal, accessTypes, null)) {
+                        mergeIntoPrincipal(policy, 
PolicyTermType.DENY_EXCEPTIONS, principalType, principal, accessTypes, 
delegateAdmin, Collections.emptyMap());
+                    }
 
-        if (CollectionUtils.isNotEmpty(policyItems)) {
-            for (RangerPolicyItem policyItem : policyItems) {
-                List<String> roles = policyItem.getRoles();
-
-                if (roles.contains(role)) {
-                    if (ret == null) {
-                        ret = new RangerPolicyItem();
-                    }
-
-                    ret.addRole(role);
-
-                    if (policyItem.getDelegateAdmin()) {
-                        ret.setDelegateAdmin(Boolean.TRUE);
+                    removeAccessesFromPrincipal(policy.getAllowExceptions(), 
policy::addAllowException, principalType, principal, accessTypes, null);

Review Comment:
   Hive GRANT ALL passes only `all` to exception removal, so an existing 
`select` allow-exception remains and still blocks SELECT despite the successful 
grant. Conversely, GRANT SELECT cannot remove SELECT from an `all` 
allow-exception. Expand the requested implied accesses and decompose composite 
exception entries before removing the granted accesses.



##########
security-admin/src/main/java/org/apache/ranger/rest/ServiceRESTUtil.java:
##########
@@ -467,731 +374,677 @@ private static void combinePolicyItems(RangerPolicy 
existingPolicy, RangerPolicy
         }
     }
 
-    private static void processApplyPolicyForItemType(RangerPolicy 
existingPolicy, RangerPolicy appliedPolicy, PolicyTermType policyItemType) {
-        LOG.debug("==> ServiceRESTUtil.processApplyPolicyForItemType()");
+    private static void compactPolicy(RangerPolicy policy) {
+        policy.setPolicyItems(mergePolicyItems(policy.getPolicyItems()));
+        
policy.setDenyPolicyItems(mergePolicyItems(policy.getDenyPolicyItems()));
+        
policy.setAllowExceptions(mergePolicyItems(policy.getAllowExceptions()));
+        policy.setDenyExceptions(mergePolicyItems(policy.getDenyExceptions()));
+    }
+
+    private static List<RangerPolicyItem> 
mergePolicyItems(List<RangerPolicyItem> policyItems) {
+        List<RangerPolicyItem> ret = new ArrayList<>();
 
-        List<RangerPolicyItem> appliedPolicyItems = null;
+        if (CollectionUtils.isNotEmpty(policyItems)) {
+            Map<String, RangerPolicyItem> matchedPolicyItems = new HashMap<>();
 
-        switch (policyItemType) {
-            case ALLOW:
-                appliedPolicyItems = appliedPolicy.getPolicyItems();
-                break;
-            case DENY:
-                appliedPolicyItems = appliedPolicy.getDenyPolicyItems();
-                break;
-            case ALLOW_EXCEPTIONS:
-                appliedPolicyItems = appliedPolicy.getAllowExceptions();
-                break;
-            case DENY_EXCEPTIONS:
-                appliedPolicyItems = appliedPolicy.getDenyExceptions();
-                break;
-            default:
-                LOG.warn("processApplyPolicyForItemType(): invalid 
policyItemType={}", policyItemType);
-        }
+            for (RangerPolicyItem policyItem : policyItems) {
+                if ((CollectionUtils.isEmpty(policyItem.getUsers()) && 
CollectionUtils.isEmpty(policyItem.getGroups()) && 
CollectionUtils.isEmpty(policyItem.getRoles())) ||
+                        (CollectionUtils.isEmpty(policyItem.getAccesses()) && 
!policyItem.getDelegateAdmin())) {
+                    continue;
+                }
 
-        if (CollectionUtils.isNotEmpty(appliedPolicyItems)) {
-            Set<String> users  = new HashSet<>();
-            Set<String> groups = new HashSet<>();
-            Set<String> roles  = new HashSet<>();
+                if (CollectionUtils.isNotEmpty(policyItem.getConditions())) {
+                    ret.add(policyItem);
+                    continue;
+                }
 
-            Map<String, RangerPolicyItem[]> userPolicyItems  = new HashMap<>();
-            Map<String, RangerPolicyItem[]> groupPolicyItems = new HashMap<>();
-            Map<String, RangerPolicyItem[]> rolePolicyItems  = new HashMap<>();
+                TreeSet<String> accesses = new TreeSet<>();
 
-            // Extract users, groups, and roles specified in appliedPolicy 
items
-            extractUsersGroupsAndRoles(appliedPolicyItems, users, groups, 
roles);
+                for (RangerPolicyItemAccess access : policyItem.getAccesses()) 
{
+                    accesses.add(access.getType());
+                }
 
-            // Split existing policyItems for users, groups, and roles 
extracted from appliedPolicyItem into userPolicyItems, groupPolicyItems, and 
rolePolicyItems
-            splitExistingPolicyItems(existingPolicy, users, userPolicyItems, 
groups, groupPolicyItems, roles, rolePolicyItems);
+                if (policyItem.getDelegateAdmin()) {
+                    accesses.add("delegateAdmin");
+                }
 
-            // Apply policyItems of given type in appliedPolicy to policyItems 
extracted from existingPolicy
-            applyPolicyItems(appliedPolicyItems, policyItemType, 
userPolicyItems, groupPolicyItems, rolePolicyItems);
+                String           allAccessesString  = accesses.toString();
+                RangerPolicyItem matchingPolicyItem = 
matchedPolicyItems.get(allAccessesString);
 
-            // Add modified/new policyItems back to existing policy
-            mergeProcessedPolicyItems(existingPolicy, userPolicyItems, 
groupPolicyItems, rolePolicyItems);
+                if (matchingPolicyItem != null) {
+                    addDistinctUsers(policyItem.getUsers(), 
matchingPolicyItem);
+                    addDistinctGroups(policyItem.getGroups(), 
matchingPolicyItem);
+                    addDistinctRoles(policyItem.getRoles(), 
matchingPolicyItem);
+                } else {
+                    matchedPolicyItems.put(allAccessesString, policyItem);
+                }
+            }
 
-            compactPolicy(existingPolicy);
+            for (Map.Entry<String, RangerPolicyItem> entry : 
matchedPolicyItems.entrySet()) {
+                ret.add(entry.getValue());
+            }
         }
 
-        LOG.debug("<== ServiceRESTUtil.processApplyPolicyForItemType()");
+        return ret;
     }
 
-    private static void mergeExactMatchPolicyForItemType(RangerPolicy 
existingPolicy, RangerPolicy appliedPolicy, PolicyTermType policyItemType) {
-        LOG.debug("==> ServiceRESTUtil.mergeExactMatchPolicyForItemType()");
-        List<RangerPolicyItem> appliedPolicyItems = null;
+    private static void addDistinctUsers(List<String> users, RangerPolicyItem 
policyItem) {
+        for (String user : users) {
+            if (!policyItem.getUsers().contains(user)) {
+                policyItem.addUser(user);
+            }
+        }
+    }
 
-        switch (policyItemType) {
-            case ALLOW:
-                appliedPolicyItems = appliedPolicy.getPolicyItems();
-                break;
-            case DENY:
-                appliedPolicyItems = appliedPolicy.getDenyPolicyItems();
-                break;
-            case ALLOW_EXCEPTIONS:
-                appliedPolicyItems = appliedPolicy.getAllowExceptions();
-                break;
-            case DENY_EXCEPTIONS:
-                appliedPolicyItems = appliedPolicy.getDenyExceptions();
-                break;
-            default:
-                LOG.warn("mergeExactMatchPolicyForItemType(): invalid 
policyItemType={}", policyItemType);
+    private static void addDistinctGroups(List<String> groups, 
RangerPolicyItem policyItem) {
+        for (String group : groups) {
+            if (!policyItem.getGroups().contains(group)) {
+                policyItem.addGroup(group);
+            }
         }
+    }
 
-        if (CollectionUtils.isNotEmpty(appliedPolicyItems)) {
-            Set<String> users  = new HashSet<>();
-            Set<String> groups = new HashSet<>();
-            Set<String> roles  = new HashSet<>();
+    private static void addDistinctRoles(List<String> roles, RangerPolicyItem 
policyItem) {
+        for (String role : roles) {
+            if (!policyItem.getRoles().contains(role)) {
+                policyItem.addRole(role);
+            }
+        }
+    }
 
-            Map<String, RangerPolicyItem[]> userPolicyItems  = new HashMap<>();
-            Map<String, RangerPolicyItem[]> groupPolicyItems = new HashMap<>();
-            Map<String, RangerPolicyItem[]> rolePolicyItems  = new HashMap<>();
+    private static boolean removeUsersGroupsAndRolesFromPolicy(RangerPolicy 
policy, Set<String> users, Set<String> groups, Set<String> roles) {
+        boolean                policyUpdated = false;
+        List<RangerPolicyItem> policyItems   = policy.getPolicyItems();
+        int                    numOfItems    = policyItems.size();
 
-            // Extract users and groups specified in appliedPolicy items
-            extractUsersGroupsAndRoles(appliedPolicyItems, users, groups, 
roles);
+        for (int i = 0; i < numOfItems; i++) {
+            RangerPolicyItem policyItem = policyItems.get(i);
 
-            // Split existing policyItems for users and groups extracted from 
appliedPolicyItem into userPolicyItems and groupPolicyItems
-            splitExistingPolicyItems(existingPolicy, users, userPolicyItems, 
groups, groupPolicyItems, roles, rolePolicyItems);
+            if (CollectionUtils.containsAny(policyItem.getUsers(), users)) {
+                policyItem.getUsers().removeAll(users);
 
-            // Apply policyItems of given type in appliedPlicy to policyItems 
extracted from existingPolicy
-            mergePolicyItems(appliedPolicyItems, policyItemType, 
userPolicyItems, groupPolicyItems, rolePolicyItems);
+                policyUpdated = true;
+            }
 
-            // Add modified/new policyItems back to existing policy
-            mergeProcessedPolicyItems(existingPolicy, userPolicyItems, 
groupPolicyItems, rolePolicyItems);
+            if (CollectionUtils.containsAny(policyItem.getGroups(), groups)) {
+                policyItem.getGroups().removeAll(groups);
 
-            compactPolicy(existingPolicy);
-        }
+                policyUpdated = true;
+            }
 
-        LOG.debug("<== ServiceRESTUtil.mergeExactMatchPolicyForItemType()");
-    }
+            if (CollectionUtils.containsAny(policyItem.getRoles(), roles)) {
+                policyItem.getRoles().removeAll(roles);
 
-    private static void extractUsersGroupsAndRoles(List<RangerPolicyItem> 
policyItems, Set<String> users, Set<String> groups, Set<String> roles) {
-        LOG.debug("==> ServiceRESTUtil.extractUsersGroupsAndRoles()");
+                policyUpdated = true;
+            }
 
-        if (CollectionUtils.isNotEmpty(policyItems)) {
-            for (RangerPolicyItem policyItem : policyItems) {
-                if (CollectionUtils.isNotEmpty(policyItem.getUsers())) {
-                    users.addAll(policyItem.getUsers());
-                }
+            if (CollectionUtils.isEmpty(policyItem.getUsers()) && 
CollectionUtils.isEmpty(policyItem.getGroups()) && 
CollectionUtils.isEmpty(policyItem.getRoles())) {
+                policyItems.remove(i);
 
-                if (CollectionUtils.isNotEmpty(policyItem.getGroups())) {
-                    groups.addAll(policyItem.getGroups());
-                }
+                numOfItems--;
+                i--;
 
-                if (CollectionUtils.isNotEmpty(policyItem.getRoles())) {
-                    roles.addAll(policyItem.getRoles());
-                }
+                policyUpdated = true;
             }
         }
 
-        LOG.debug("<== ServiceRESTUtil.extractUsersGroupsAndRoles()");
+        return policyUpdated;
     }
 
-    private static void splitExistingPolicyItems(RangerPolicy existingPolicy, 
Set<String> users, Map<String, RangerPolicyItem[]> userPolicyItems, Set<String> 
groups, Map<String, RangerPolicyItem[]> groupPolicyItems, Set<String> roles, 
Map<String, RangerPolicyItem[]> rolePolicyItems) {
-        if (existingPolicy == null || users == null || userPolicyItems == null 
|| groups == null || groupPolicyItems == null || roles == null || 
rolePolicyItems == null) {
-            return;
-        }
-
-        LOG.debug("==> ServiceRESTUtil.splitExistingPolicyItems()");
+    /**
+     * Returns the effective permissions of the policy as a set of (term, 
principal, accessType, delegateAdmin, conditions)
+     * entries; independent of how principals are grouped into policy items 
and compared by effective permission rather
+     * than by stored access name: an access type that implies others (Hive's 
all) stands for the access types it implies, and the grant
+     * option of an access type is combined (logical or) over all items of the 
same term, principal and conditions.
+     * An access type that is held both through "all" and individually is 
therefore a single permission.
+     */
+    static Set<String> getPermissionSet(RangerPolicy policy, Map<String, 
Set<String>> impliedGrants) {
+        Map<String, Boolean> permissions = new HashMap<>();
 
-        List<RangerPolicyItem> allowItems          = 
existingPolicy.getPolicyItems();
-        List<RangerPolicyItem> denyItems           = 
existingPolicy.getDenyPolicyItems();
-        List<RangerPolicyItem> allowExceptionItems = 
existingPolicy.getAllowExceptions();
-        List<RangerPolicyItem> denyExceptionItems  = 
existingPolicy.getDenyExceptions();
+        addPermissions(permissions, PolicyTermType.ALLOW, 
policy.getPolicyItems(), impliedGrants);
+        addPermissions(permissions, PolicyTermType.DENY, 
policy.getDenyPolicyItems(), impliedGrants);
+        addPermissions(permissions, PolicyTermType.ALLOW_EXCEPTIONS, 
policy.getAllowExceptions(), impliedGrants);
+        addPermissions(permissions, PolicyTermType.DENY_EXCEPTIONS, 
policy.getDenyExceptions(), impliedGrants);
 
-        for (String user : users) {
-            RangerPolicyItem[] value = userPolicyItems.computeIfAbsent(user, k 
-> new RangerPolicyItem[4]);
-            RangerPolicyItem   policyItem;
-
-            policyItem                                       = 
splitAndGetConsolidatedPolicyItemForUser(allowItems, user);
-            value[PolicyTermType.ALLOW.ordinal()]            = policyItem;
-            policyItem                                       = 
splitAndGetConsolidatedPolicyItemForUser(denyItems, user);
-            value[PolicyTermType.DENY.ordinal()]             = policyItem;
-            policyItem                                       = 
splitAndGetConsolidatedPolicyItemForUser(allowExceptionItems, user);
-            value[PolicyTermType.ALLOW_EXCEPTIONS.ordinal()] = policyItem;
-            policyItem                                       = 
splitAndGetConsolidatedPolicyItemForUser(denyExceptionItems, user);
-            value[PolicyTermType.DENY_EXCEPTIONS.ordinal()]  = policyItem;
-        }
+        Set<String> ret = new HashSet<>();
 
-        for (String group : groups) {
-            RangerPolicyItem[] value = groupPolicyItems.computeIfAbsent(group, 
k -> new RangerPolicyItem[4]);
-            RangerPolicyItem   policyItem;
-
-            policyItem                                       = 
splitAndGetConsolidatedPolicyItemForGroup(allowItems, group);
-            value[PolicyTermType.ALLOW.ordinal()]            = policyItem;
-            policyItem                                       = 
splitAndGetConsolidatedPolicyItemForGroup(denyItems, group);
-            value[PolicyTermType.DENY.ordinal()]             = policyItem;
-            policyItem                                       = 
splitAndGetConsolidatedPolicyItemForGroup(allowExceptionItems, group);
-            value[PolicyTermType.ALLOW_EXCEPTIONS.ordinal()] = policyItem;
-            policyItem                                       = 
splitAndGetConsolidatedPolicyItemForGroup(denyExceptionItems, group);
-            value[PolicyTermType.DENY_EXCEPTIONS.ordinal()]  = policyItem;
-        }
-        for (String role : roles) {
-            RangerPolicyItem[] value = rolePolicyItems.computeIfAbsent(role, k 
-> new RangerPolicyItem[4]);
-            RangerPolicyItem   policyItem;
-
-            policyItem                                       = 
splitAndGetConsolidatedPolicyItemForRole(allowItems, role);
-            value[PolicyTermType.ALLOW.ordinal()]            = policyItem;
-            policyItem                                       = 
splitAndGetConsolidatedPolicyItemForRole(denyItems, role);
-            value[PolicyTermType.DENY.ordinal()]             = policyItem;
-            policyItem                                       = 
splitAndGetConsolidatedPolicyItemForRole(allowExceptionItems, role);
-            value[PolicyTermType.ALLOW_EXCEPTIONS.ordinal()] = policyItem;
-            policyItem                                       = 
splitAndGetConsolidatedPolicyItemForRole(denyExceptionItems, role);
-            value[PolicyTermType.DENY_EXCEPTIONS.ordinal()]  = policyItem;
+        for (Map.Entry<String, Boolean> entry : permissions.entrySet()) {
+            ret.add(entry.getKey() + "|delegateAdmin=" + entry.getValue());
         }
 
-        LOG.debug("<== ServiceRESTUtil.splitExistingPolicyItems()");
+        return ret;
     }
 
-    private static RangerPolicyItem 
splitAndGetConsolidatedPolicyItemForUser(List<RangerPolicyItem> policyItems, 
String user) {
-        LOG.debug("==> 
ServiceRESTUtil.splitAndGetConsolidatedPolicyItemForUser()");
+    private static void addPermissions(Map<String, Boolean> permissions, 
PolicyTermType termType, List<RangerPolicyItem> policyItems, Map<String, 
Set<String>> impliedGrants) {
+        for (RangerPolicyItem policyItem : policyItems) {
+            Set<String> accessTypes = new TreeSet<>();
 
-        RangerPolicyItem ret = null;
+            for (String accessType : getAllowedAccessTypes(policyItem)) {
+                Set<String> implied = impliedGrants.get(accessType);
 
-        if (CollectionUtils.isNotEmpty(policyItems)) {
-            for (RangerPolicyItem policyItem : policyItems) {
-                List<String> users = policyItem.getUsers();
+                if (implied != null) {
+                    accessTypes.addAll(implied);

Review Comment:
   If a user already holds every privilege implied by Hive `all` with grant 
option, `GRANT ALL ... WITH GRANT OPTION` is treated as unchanged, so the `all` 
entry is not persisted. Grant/revoke authorization still checks literal `all`, 
leaving that user unable to GRANT/REVOKE ALL despite the successful response. 
Either authorize ALL using the same composite expansion or preserve its literal 
entry in change detection.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to