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


##########
security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyAdminImpl.java:
##########
@@ -826,6 +826,7 @@ private Set<String> getAllModifiedAccessTypes(RangerPolicy 
oldPolicy, RangerPoli
         ret.addAll(getAccessTypesDiff(newUserAccesses, oldUserAccesses));
         ret.addAll(getAccessTypesDiff(newGroupAccesses, oldGroupAccesses));
         ret.addAll(getAccessTypesDiff(newRoleAccesses, oldRoleAccesses));
+        ret.addAll(getDelegatedAccessTypesDiff(oldPolicy, policy, serviceDef));

Review Comment:
   A nonempty grant-option delta suppresses full-policy authorization even when 
unrelated item conditions or allow/deny terms change. For example, clearing 
Bob's SELECT grant option while removing a condition from his delegated UPDATE 
item yields only SELECT; Bob remains a delegated principal, so a SELECT-only 
administrator can widen UPDATE access. Include condition and term changes in 
the authorized delta, or require full-policy authorization for those changes.



##########
security-admin/src/main/java/org/apache/ranger/rest/ServiceRESTUtil.java:
##########
@@ -46,171 +52,118 @@ private ServiceRESTUtil() {
         //To block instantiation
     }
 
+    /**
+     * Applies a grant request to the given policy.
+     *
+     * @return true if the policy's effective permissions changed, false if 
the grant was a no-op
+     */
     public static boolean processGrantRequest(RangerPolicy policy, 
GrantRevokeRequest grantRequest) {
+        return processGrantRequest(policy, grantRequest, null);
+    }
+
+    /**
+     * Same as {@link #processGrantRequest(RangerPolicy, GrantRevokeRequest)}, 
but honors Hive's "all", which implies
+     * other access types: granting an access type that a principal already 
holds through "all" is a no-op, and
+     * granting "all" replaces the principal's individually granted implied 
access types.
+     *
+     * @param serviceDef service-def of the policy's service; access types are 
matched by name only when it is null
+     *                   or not Hive's
+     */
+    public static boolean processGrantRequest(RangerPolicy policy, 
GrantRevokeRequest grantRequest, RangerServiceDef serviceDef) {
         LOG.debug("==> ServiceRESTUtil.processGrantRequest()");
 
+        Set<String> permissionsBefore = getPermissionSet(policy);
+
         // replace all existing privileges for users, groups, and roles
         if (grantRequest.getReplaceExistingPermissions()) {
             removeUsersGroupsAndRolesFromPolicy(policy, 
grantRequest.getUsers(), grantRequest.getGroups(), grantRequest.getRoles());
         }
 
-        //Build a policy and set up policyItem in it to mimic grant request
-        RangerPolicy     appliedPolicy = new RangerPolicy();
-        RangerPolicyItem policyItem    = new RangerPolicyItem();
-
-        policyItem.setDelegateAdmin(grantRequest.getDelegateAdmin());
-        policyItem.addUsers(grantRequest.getUsers());
-        policyItem.addGroups(grantRequest.getGroups());
-        policyItem.addRoles(grantRequest.getRoles());
+        Set<String> accessTypes   = grantRequest.getAccessTypes();
+        boolean     delegateAdmin = 
Boolean.TRUE.equals(grantRequest.getDelegateAdmin());
 
-        List<RangerPolicyItemAccess> accesses = new ArrayList<>();
+        if (containsRangerCondition(policy)) {
+            // splitting principals out of conditional items could drop or 
widen conditions; append the grant as a separate item instead
+            RangerPolicy appliedPolicy = new RangerPolicy();
 
-        for (String accessType : grantRequest.getAccessTypes()) {
-            accesses.add(new RangerPolicyItemAccess(accessType, true));
-        }
+            
appliedPolicy.addPolicyItem(createPolicyItem(grantRequest.getUsers(), 
grantRequest.getGroups(), grantRequest.getRoles(), accessTypes, delegateAdmin));
 
-        policyItem.setAccesses(accesses);
+            combinePolicy(policy, appliedPolicy);
+        } else {
+            Map<String, Set<String>> impliedGrants = 
getImpliedGrants(serviceDef);
 
-        appliedPolicy.addPolicyItem(policyItem);
+            for (PrincipalType principalType : PrincipalType.values()) {
+                for (String principal : 
principalType.getPrincipals(grantRequest)) {
+                    grantToPrincipal(policy, principalType, principal, 
accessTypes, delegateAdmin, impliedGrants);
+                }
+            }
 
-        processApplyPolicy(policy, appliedPolicy);
+            compactPolicy(policy);
+        }
 
-        boolean policyUpdated = true;
+        boolean policyUpdated = 
!permissionsBefore.equals(getPermissionSet(policy));

Review Comment:
   The before/after sets compare stored access names rather than effective Hive 
permissions, so regranting SELECT to a principal holding both ALL and redundant 
SELECT removes the redundant entry and incorrectly returns true. This triggers 
`ensureAdminAccess()`, whose empty effective delta requires every ALL privilege 
and rejects a SELECT-only grantor for a no-op. Expand Hive implications and 
combine grant-option state per term, principal, and condition before comparing 
permissions.



##########
security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyAdminImpl.java:
##########
@@ -826,6 +826,7 @@ private Set<String> getAllModifiedAccessTypes(RangerPolicy 
oldPolicy, RangerPoli
         ret.addAll(getAccessTypesDiff(newUserAccesses, oldUserAccesses));
         ret.addAll(getAccessTypesDiff(newGroupAccesses, oldGroupAccesses));
         ret.addAll(getAccessTypesDiff(newRoleAccesses, oldRoleAccesses));
+        ret.addAll(getDelegatedAccessTypesDiff(oldPolicy, policy, serviceDef));

Review Comment:
   The narrower authorization is bypassed when a principal gains their first 
grant option or loses their last one: `isPolicyScopeChanged()` compares 
delegated-principal sets and takes the full-policy authorization branch before 
reaching this line. For example, revoking the grant option on Bob's SELECT 
while he also holds UPDATE without a grant option still requires UPDATE 
authority. Update the scope check so access-specific grant-option changes use 
this delta, and cover first/last grant-option transitions.



##########
security-admin/src/main/java/org/apache/ranger/rest/ServiceRESTUtil.java:
##########
@@ -467,731 +375,658 @@ 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()");
-
-        List<RangerPolicyItem> allowItems          = 
existingPolicy.getPolicyItems();
-        List<RangerPolicyItem> denyItems           = 
existingPolicy.getDenyPolicyItems();
-        List<RangerPolicyItem> allowExceptionItems = 
existingPolicy.getAllowExceptions();
-        List<RangerPolicyItem> denyExceptionItems  = 
existingPolicy.getDenyExceptions();
-
-        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;
-        }
+    /**
+     * 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.
+     */
+    static Set<String> getPermissionSet(RangerPolicy policy) {
+        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;
-        }
+        addPermissions(ret, PolicyTermType.ALLOW, policy.getPolicyItems());
+        addPermissions(ret, PolicyTermType.DENY, policy.getDenyPolicyItems());
+        addPermissions(ret, PolicyTermType.ALLOW_EXCEPTIONS, 
policy.getAllowExceptions());
+        addPermissions(ret, PolicyTermType.DENY_EXCEPTIONS, 
policy.getDenyExceptions());
 
-        LOG.debug("<== ServiceRESTUtil.splitExistingPolicyItems()");
+        return ret;
     }
 
-    private static RangerPolicyItem 
splitAndGetConsolidatedPolicyItemForUser(List<RangerPolicyItem> policyItems, 
String user) {
-        LOG.debug("==> 
ServiceRESTUtil.splitAndGetConsolidatedPolicyItemForUser()");
-
-        RangerPolicyItem ret = null;
-
-        if (CollectionUtils.isNotEmpty(policyItems)) {
-            for (RangerPolicyItem policyItem : policyItems) {
-                List<String> users = policyItem.getUsers();
+    private static void addPermissions(Set<String> permissions, PolicyTermType 
termType, List<RangerPolicyItem> policyItems) {
+        for (RangerPolicyItem policyItem : policyItems) {
+            List<String> accessTypes = getAllowedAccessTypes(policyItem);
 
-                if (users.contains(user)) {
-                    if (ret == null) {
-                        ret = new RangerPolicyItem();
-                    }
+            if (accessTypes.isEmpty() && policyItem.getDelegateAdmin()) {
+                accessTypes = Collections.singletonList("");
+            }
 
-                    ret.addUser(user);
+            String suffix = "|delegateAdmin=" + policyItem.getDelegateAdmin() 
+ "|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.add(termType + "|" + principalType + "|" + 
principal + "|" + accessType + suffix);
                     }
-
-                    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 (CollectionUtils.isNotEmpty(policyItems)) {
-            for (RangerPolicyItem policyItem : policyItems) {
-                List<String> roles = policyItem.getRoles();
-
-                if (roles.contains(role)) {
-                    if (ret == null) {
-                        ret = new RangerPolicyItem();
+        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());
                     }
 
-                    ret.addRole(role);
-
-                    if (policyItem.getDelegateAdmin()) {
-                        ret.setDelegateAdmin(Boolean.TRUE);
+                    removeAccessesFromPrincipal(policy.getAllowExceptions(), 
policy::addAllowException, principalType, principal, accessTypes, null);
+                    break;
+                case DENY:
+                    // denied accesses override the principal's own allow and 
deny-exception entries
+                    if (removeAccessesFromPrincipal(policy.getPolicyItems(), 
policy::addPolicyItem, principalType, principal, accessTypes, null)) {
+                        mergeIntoPrincipal(policy, 
PolicyTermType.ALLOW_EXCEPTIONS, principalType, principal, accessTypes, 
delegateAdmin, Collections.emptyMap());
                     }
 
-                    addAccesses(ret, policyItem.getAccesses());
-
-                    // Remove this role from existingPolicyItem
-                    roles.remove(role);
-                }
+                    removeAccessesFromPrincipal(policy.getDenyExceptions(), 
policy::addDenyException, principalType, principal, accessTypes, null);
+                    break;
+                case ALLOW_EXCEPTIONS:
+                    removeAccessesFromPrincipal(policy.getPolicyItems(), 
policy::addPolicyItem, principalType, principal, accessTypes, null);
+                    break;
+                case DENY_EXCEPTIONS:
+                    removeAccessesFromPrincipal(policy.getDenyPolicyItems(), 
policy::addDenyPolicyItem, principalType, principal, accessTypes, null);
+                    break;
+                default:
+                    LOG.warn("applyToPrincipal(): invalid termType={}", 
termType);
+                    break;
             }
         }
-
-        LOG.debug("<== 
ServiceRESTUtil.splitAndGetConsolidatedPolicyItemForGroup()");
-
-        return ret;
     }
 
-    private static void applyPolicyItems(List<RangerPolicyItem> 
appliedPolicyItems, PolicyTermType policyItemType, Map<String, 
RangerPolicyItem[]> existingUserPolicyItems, Map<String, RangerPolicyItem[]> 
existingGroupPolicyItems, Map<String, RangerPolicyItem[]> 
existingRolePolicyItems) {
-        LOG.debug("==> ServiceRESTUtil.applyPolicyItems()");
-
-        for (RangerPolicyItem policyItem : appliedPolicyItems) {
-            List<String> users = policyItem.getUsers();
-
-            for (String user : users) {
-                RangerPolicyItem[] existingPolicyItems = 
existingUserPolicyItems.get(user);
-
-                if (existingPolicyItems == null) {
-                    // Should not get here
-                    LOG.warn("Should not have come here..");
+    /**
+     * Adds accessTypes to the principal's items of the given term type. The 
principal's existing items of the term
+     * type are consolidated, with delegateAdmin tracked per access type so 
that delegateAdmin of one item doesn't
+     * extend to accesses held through other items. Principals sharing an item 
with the principal are not affected.
+     */
+    private static void mergeIntoPrincipal(RangerPolicy policy, PolicyTermType 
termType, PrincipalType principalType, String principal, Set<String> 
accessTypes, boolean delegateAdmin, Map<String, Set<String>> impliedGrants) {
+        Map<String, Boolean> accessTypeDelegateAdmin = new TreeMap<>();
+        boolean              delegateAdminOnly       = accessTypes.isEmpty() 
&& delegateAdmin;
 
-                    existingPolicyItems = new RangerPolicyItem[4];
+        for (RangerPolicyItem policyItem : getPolicyItems(policy, termType)) {
+            if (principalType.getPrincipals(policyItem).contains(principal)) {
+                List<String> itemAccessTypes = 
getAllowedAccessTypes(policyItem);
 
-                    existingUserPolicyItems.put(user, existingPolicyItems);
+                for (String accessType : itemAccessTypes) {
+                    accessTypeDelegateAdmin.merge(accessType, 
policyItem.getDelegateAdmin(), Boolean::logicalOr);
                 }
 
-                addPolicyItemForUser(existingPolicyItems, 
policyItemType.ordinal(), user, policyItem);
+                if (itemAccessTypes.isEmpty() && 
policyItem.getDelegateAdmin()) {
+                    delegateAdminOnly = true;
+                }
 
-                switch (policyItemType) {
-                    case ALLOW:
-                        RangerPolicyItem denyPolicyItem = 
existingPolicyItems[PolicyTermType.DENY.ordinal()];
+                principalType.removePrincipal(policyItem, principal);
+            }
+        }
 
-                        if (denyPolicyItem != null) {
-                            
removeAccesses(existingPolicyItems[PolicyTermType.DENY.ordinal()], 
policyItem.getAccesses());
-                            addPolicyItemForUser(existingPolicyItems, 
PolicyTermType.DENY_EXCEPTIONS.ordinal(), user, policyItem);
-                        }
+        for (String accessType : accessTypes) {
+            accessTypeDelegateAdmin.merge(accessType, delegateAdmin, 
Boolean::logicalOr);
+        }
 
-                        
removeAccesses(existingPolicyItems[PolicyTermType.ALLOW_EXCEPTIONS.ordinal()], 
policyItem.getAccesses());
-                        break;
-                    case DENY:
-                        RangerPolicyItem allowPolicyItem = 
existingPolicyItems[PolicyTermType.ALLOW.ordinal()];
+        removeRedundantImpliedAccessTypes(accessTypeDelegateAdmin, 
accessTypes, impliedGrants);
 
-                        if (allowPolicyItem != null) {
-                            
removeAccesses(existingPolicyItems[PolicyTermType.ALLOW.ordinal()], 
policyItem.getAccesses());
-                            addPolicyItemForUser(existingPolicyItems, 
PolicyTermType.ALLOW_EXCEPTIONS.ordinal(), user, policyItem);
-                        }
+        Set<String> delegatedAccessTypes    = new TreeSet<>();
+        Set<String> nonDelegatedAccessTypes = new TreeSet<>();
 
-                        
removeAccesses(existingPolicyItems[PolicyTermType.DENY_EXCEPTIONS.ordinal()], 
policyItem.getAccesses());
-                        break;
-                    case ALLOW_EXCEPTIONS:
-                        
removeAccesses(existingPolicyItems[PolicyTermType.ALLOW.ordinal()], 
policyItem.getAccesses());
-                        break;
-                    case DENY_EXCEPTIONS:
-                        
removeAccesses(existingPolicyItems[PolicyTermType.DENY.ordinal()], 
policyItem.getAccesses());
-                        break;
-                    default:
-                        LOG.warn("Should not have come here..");
-                        break;
-                }
+        for (Map.Entry<String, Boolean> entry : 
accessTypeDelegateAdmin.entrySet()) {
+            if (entry.getValue()) {
+                delegatedAccessTypes.add(entry.getKey());
+            } else {
+                nonDelegatedAccessTypes.add(entry.getKey());
             }
         }
 
-        for (RangerPolicyItem policyItem : appliedPolicyItems) {
-            List<String> groups = policyItem.getGroups();
+        if (!delegatedAccessTypes.isEmpty() || delegateAdminOnly) {
+            addPolicyItem(policy, termType, createPolicyItem(principalType, 
principal, delegatedAccessTypes, true));
+        }
 
-            for (String group : groups) {
-                RangerPolicyItem[] existingPolicyItems = 
existingGroupPolicyItems.computeIfAbsent(group, k -> new RangerPolicyItem[4]);
+        if (!nonDelegatedAccessTypes.isEmpty()) {
+            addPolicyItem(policy, termType, createPolicyItem(principalType, 
principal, nonDelegatedAccessTypes, false));
+        }
+    }
 
-                // Should not get here
+    private static List<RangerPolicyItem> getPolicyItems(RangerPolicy policy, 
PolicyTermType termType) {
+        final List<RangerPolicyItem> ret;
 
-                addPolicyItemForGroup(existingPolicyItems, 
policyItemType.ordinal(), group, policyItem);
+        switch (termType) {
+            case ALLOW:
+                ret = policy.getPolicyItems();
+                break;
+            case DENY:
+                ret = policy.getDenyPolicyItems();
+                break;
+            case ALLOW_EXCEPTIONS:
+                ret = policy.getAllowExceptions();
+                break;
+            case DENY_EXCEPTIONS:
+                ret = policy.getDenyExceptions();
+                break;
+            default:
+                LOG.warn("getPolicyItems(): invalid termType={}", termType);
 
-                switch (policyItemType) {
-                    case ALLOW:
-                        RangerPolicyItem denyPolicyItem = 
existingPolicyItems[PolicyTermType.DENY.ordinal()];
+                ret = Collections.emptyList();
+                break;
+        }
 
-                        if (denyPolicyItem != null) {
-                            
removeAccesses(existingPolicyItems[PolicyTermType.DENY.ordinal()], 
policyItem.getAccesses());
-                            addPolicyItemForGroup(existingPolicyItems, 
PolicyTermType.DENY_EXCEPTIONS.ordinal(), group, policyItem);
-                        }
+        return ret;
+    }
 
-                        
removeAccesses(existingPolicyItems[PolicyTermType.ALLOW_EXCEPTIONS.ordinal()], 
policyItem.getAccesses());
-                        break;
-                    case DENY:
-                        RangerPolicyItem allowPolicyItem = 
existingPolicyItems[PolicyTermType.ALLOW.ordinal()];
+    private static void addPolicyItem(RangerPolicy policy, PolicyTermType 
termType, RangerPolicyItem policyItem) {
+        switch (termType) {
+            case ALLOW:
+                policy.addPolicyItem(policyItem);
+                break;
+            case DENY:
+                policy.addDenyPolicyItem(policyItem);
+                break;
+            case ALLOW_EXCEPTIONS:
+                policy.addAllowException(policyItem);
+                break;
+            case DENY_EXCEPTIONS:
+                policy.addDenyException(policyItem);
+                break;
+            default:
+                LOG.warn("addPolicyItem(): invalid termType={}", termType);
+                break;
+        }
+    }
 
-                        if (allowPolicyItem != null) {
-                            
removeAccesses(existingPolicyItems[PolicyTermType.ALLOW.ordinal()], 
policyItem.getAccesses());
-                            addPolicyItemForGroup(existingPolicyItems, 
PolicyTermType.ALLOW_EXCEPTIONS.ordinal(), group, policyItem);
-                        }
+    /**
+     * Removes access types that are already covered by an implying access 
type (e.g. select by all) held with at least
+     * the same grant option. Only access types involved in the request are 
considered, so that unrelated pre-existing
+     * entries are left untouched.
+     */
+    private static void removeRedundantImpliedAccessTypes(Map<String, Boolean> 
accessTypeDelegateAdmin, Set<String> requestedAccessTypes, Map<String, 
Set<String>> impliedGrants) {
+        Set<String> redundant = new HashSet<>();
 
-                        
removeAccesses(existingPolicyItems[PolicyTermType.DENY_EXCEPTIONS.ordinal()], 
policyItem.getAccesses());
-                        break;
-                    case ALLOW_EXCEPTIONS:
-                        
removeAccesses(existingPolicyItems[PolicyTermType.ALLOW.ordinal()], 
policyItem.getAccesses());
-                        break;
-                    case DENY_EXCEPTIONS:
-                        
removeAccesses(existingPolicyItems[PolicyTermType.DENY.ordinal()], 
policyItem.getAccesses());
-                        break;
-                    default:
-                        break;
+        for (Map.Entry<String, Boolean> implying : 
accessTypeDelegateAdmin.entrySet()) {
+            Set<String> implied = impliedGrants.get(implying.getKey());
+
+            if (implied != null) {
+                for (String impliedAccessType : implied) {
+                    Boolean impliedDelegateAdmin = 
accessTypeDelegateAdmin.get(impliedAccessType);
+
+                    if (impliedDelegateAdmin != null && (implying.getValue() 
|| !impliedDelegateAdmin) && (requestedAccessTypes.contains(impliedAccessType) 
|| requestedAccessTypes.contains(implying.getKey()))) {
+                        redundant.add(impliedAccessType);
+                    }
                 }
             }
         }
 
-        for (RangerPolicyItem policyItem : appliedPolicyItems) {
-            List<String> roles = policyItem.getRoles();
-
-            for (String role : roles) {
-                RangerPolicyItem[] existingPolicyItems = 
existingRolePolicyItems.computeIfAbsent(role, k -> new RangerPolicyItem[4]);
+        accessTypeDelegateAdmin.keySet().removeAll(redundant);
+    }
 
-                // Should not get here
+    /**
+     * Removes accessTypes from the principal in the given items. The 
principal is split out of items it shares with
+     * other principals, retaining the item's conditions.
+     *
+     * @param delegateAdmin value to set on the principal's remaining 
accesses; null to retain the item's value
+     * @return true if the principal is present in any of the given items
+     */
+    private static boolean removeAccessesFromPrincipal(List<RangerPolicyItem> 
policyItems, Consumer<RangerPolicyItem> addPolicyItem, PrincipalType 
principalType, String principal, Set<String> accessTypes, Boolean 
delegateAdmin) {
+        boolean                ret      = false;
+        List<RangerPolicyItem> newItems = new ArrayList<>();
 
-                addPolicyItemForRole(existingPolicyItems, 
policyItemType.ordinal(), role, policyItem);
+        for (RangerPolicyItem policyItem : policyItems) {
+            if (principalType.getPrincipals(policyItem).contains(principal)) {
+                ret = true;
 
-                switch (policyItemType) {
-                    case ALLOW:
-                        RangerPolicyItem denyPolicyItem = 
existingPolicyItems[PolicyTermType.DENY.ordinal()];
+                if (containsAnyAccessType(policyItem, accessTypes)) {
+                    RangerPolicyItem principalItem = 
copyForPrincipal(policyItem, principalType, principal);
 
-                        if (denyPolicyItem != null) {
-                            
removeAccesses(existingPolicyItems[PolicyTermType.DENY.ordinal()], 
policyItem.getAccesses());
-                            addPolicyItemForRole(existingPolicyItems, 
PolicyTermType.DENY_EXCEPTIONS.ordinal(), role, policyItem);
-                        }
+                    principalItem.getAccesses().removeIf(access -> 
accessTypes.contains(access.getType()));
 
-                        
removeAccesses(existingPolicyItems[PolicyTermType.ALLOW_EXCEPTIONS.ordinal()], 
policyItem.getAccesses());
-                        break;
-                    case DENY:
-                        RangerPolicyItem allowPolicyItem = 
existingPolicyItems[PolicyTermType.ALLOW.ordinal()];
+                    if (delegateAdmin != null) {
+                        principalItem.setDelegateAdmin(delegateAdmin);
+                    }
 
-                        if (allowPolicyItem != null) {
-                            
removeAccesses(existingPolicyItems[PolicyTermType.ALLOW.ordinal()], 
policyItem.getAccesses());
-                            addPolicyItemForRole(existingPolicyItems, 
PolicyTermType.ALLOW_EXCEPTIONS.ordinal(), role, policyItem);
-                        }
+                    if (!principalItem.getAccesses().isEmpty()) {
+                        newItems.add(principalItem);
+                    }
 
-                        
removeAccesses(existingPolicyItems[PolicyTermType.DENY_EXCEPTIONS.ordinal()], 
policyItem.getAccesses());
-                        break;
-                    case ALLOW_EXCEPTIONS:
-                        
removeAccesses(existingPolicyItems[PolicyTermType.ALLOW.ordinal()], 
policyItem.getAccesses());
-                        break;
-                    case DENY_EXCEPTIONS:
-                        
removeAccesses(existingPolicyItems[PolicyTermType.DENY.ordinal()], 
policyItem.getAccesses());
-                        break;
-                    default:
-                        break;
+                    principalType.removePrincipal(policyItem, principal);
                 }
             }
         }
 
-        LOG.debug("<== ServiceRESTUtil.applyPolicyItems()");
+        newItems.forEach(addPolicyItem);
+
+        return ret;
     }
 
-    private static void mergePolicyItems(List<RangerPolicyItem> 
appliedPolicyItems, PolicyTermType policyItemType, Map<String, 
RangerPolicyItem[]> existingUserPolicyItems, Map<String, RangerPolicyItem[]> 
existingGroupPolicyItems, Map<String, RangerPolicyItem[]> 
existingRolePolicyItems) {
-        LOG.debug("==> ServiceRESTUtil.mergePolicyItems()");
+    /**
+     * Revokes only the grant option (delegateAdmin) on accessTypes from the 
principal; the accesses are retained.
+     * Other accesses in the same item keep their delegateAdmin.
+     */
+    private static void revokeDelegateAdminFromPrincipal(RangerPolicy policy, 
PrincipalType principalType, String principal, Set<String> accessTypes) {
+        List<RangerPolicyItem> newItems = new ArrayList<>();
 
-        for (RangerPolicyItem policyItem : appliedPolicyItems) {
-            List<String> users = policyItem.getUsers();
+        for (RangerPolicyItem policyItem : policy.getPolicyItems()) {
+            if (policyItem.getDelegateAdmin() && 
principalType.getPrincipals(policyItem).contains(principal) && 
containsAnyAccessType(policyItem, accessTypes)) {
+                RangerPolicyItem revokedItem  = copyForPrincipal(policyItem, 
principalType, principal);
+                RangerPolicyItem retainedItem = copyForPrincipal(policyItem, 
principalType, principal);
 
-            for (String user : users) {
-                RangerPolicyItem[] items = existingUserPolicyItems.get(user);
+                revokedItem.getAccesses().removeIf(access -> 
!accessTypes.contains(access.getType()));
+                revokedItem.setDelegateAdmin(Boolean.FALSE);
 
-                if (items == null) {
-                    // Should not get here
-                    LOG.warn("Should not have come here..");
+                retainedItem.getAccesses().removeIf(access -> 
accessTypes.contains(access.getType()));
 
-                    items = new RangerPolicyItem[4];
+                newItems.add(revokedItem);
 
-                    existingUserPolicyItems.put(user, items);
+                if (!retainedItem.getAccesses().isEmpty()) {
+                    newItems.add(retainedItem);
                 }
 
-                addPolicyItemForUser(items, policyItemType.ordinal(), user, 
policyItem);
+                principalType.removePrincipal(policyItem, principal);
             }
         }
 
-        for (RangerPolicyItem policyItem : appliedPolicyItems) {
-            List<String> groups = policyItem.getGroups();
+        newItems.forEach(policy::addPolicyItem);
+    }
 
-            for (String group : groups) {
-                RangerPolicyItem[] items = 
existingGroupPolicyItems.computeIfAbsent(group, k -> new RangerPolicyItem[4]);
+    /**
+     * Returns the access types that imply other access types, by name. Only 
Hive is supported: its composite "all"
+     * stands for a flat set of access types, so granting or revoking them 
individually is well defined. In other
+     * services an access type that implies another is an independent action 
(e.g. Kafka publish implies describe,
+     * Polaris implications are nested), and decomposing it would silently 
change unrelated permissions; for those
+     * services access types are matched by name only.
+     */
+    private static Map<String, Set<String>> getImpliedGrants(RangerServiceDef 
serviceDef) {
+        Map<String, Set<String>> ret = new HashMap<>();
 
-                // Should not get here
-                addPolicyItemForGroup(items, policyItemType.ordinal(), group, 
policyItem);
+        if (serviceDef != null && serviceDef.getAccessTypes() != null && 
StringUtils.equalsIgnoreCase(serviceDef.getName(), 
EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_HIVE_NAME)) {
+            for (RangerAccessTypeDef accessTypeDef : 
serviceDef.getAccessTypes()) {
+                if 
(CollectionUtils.isNotEmpty(accessTypeDef.getImpliedGrants())) {
+                    ret.put(accessTypeDef.getName(), new 
HashSet<>(accessTypeDef.getImpliedGrants()));
+                }
             }
         }
 
-        for (RangerPolicyItem policyItem : appliedPolicyItems) {
-            List<String> roles = policyItem.getRoles();
+        return ret;
+    }
+
+    /**
+     * Returns accessTypes along with the access types they imply.
+     */
+    private static Set<String> addImpliedAccessTypes(Set<String> accessTypes, 
Map<String, Set<String>> impliedGrants) {
+        Set<String> ret = new HashSet<>(accessTypes);
 
-            for (String role : roles) {
-                RangerPolicyItem[] items = 
existingRolePolicyItems.computeIfAbsent(role, k -> new RangerPolicyItem[4]);
+        for (String accessType : accessTypes) {
+            Set<String> implied = impliedGrants.get(accessType);
 
-                // Should not get here
-                addPolicyItemForRole(items, policyItemType.ordinal(), role, 
policyItem);
+            if (implied != null) {
+                ret.addAll(implied);
             }
         }
 
-        LOG.debug("<== ServiceRESTUtil.mergePolicyItems()");
+        return ret;
     }
 
-    private static void mergeProcessedPolicyItems(RangerPolicy existingPolicy, 
Map<String, RangerPolicyItem[]> userPolicyItems, Map<String, 
RangerPolicyItem[]> groupPolicyItems, Map<String, RangerPolicyItem[]> 
rolePolicyItems) {
-        LOG.debug("==> ServiceRESTUtil.mergeProcessedPolicyItems()");
+    /**
+     * Replaces access types in the given items that imply a to-be-revoked 
access type (e.g. all) with the access types
+     * they imply, so that revoking one of the implied access types leaves the 
others in place.
+     * The principal is split out of items shared with other principals, so 
that only the principal's accesses are expanded.
+     * An entry of the implying access type that is not allowed 
(isAllowed=false) is still granted through the implying
+     * access type, so it is replaced with an allowed entry in the expanded 
list; the original item is not modified.
+     *
+     * @param delegatedItemsOnly expand only items with delegateAdmin set; 
used when only the grant option is revoked,
+     *                           so that items without a grant option are left 
as they are
+     */
+    private static void expandImpliedAccesses(List<RangerPolicyItem> 
policyItems, Consumer<RangerPolicyItem> addPolicyItem, PrincipalType 
principalType, String principal, Set<String> accessTypesToRevoke, Map<String, 
Set<String>> impliedGrants, boolean delegatedItemsOnly) {
+        if (!impliedGrants.isEmpty()) {
+            List<RangerPolicyItem> newItems = new ArrayList<>();
 
-        for (Map.Entry<String, RangerPolicyItem[]> entry : 
userPolicyItems.entrySet()) {
-            RangerPolicyItem[] items = entry.getValue();
-            RangerPolicyItem   item;
+            for (RangerPolicyItem policyItem : policyItems) {
+                if 
(principalType.getPrincipals(policyItem).contains(principal) && 
(!delegatedItemsOnly || Boolean.TRUE.equals(policyItem.getDelegateAdmin()))) {
+                    List<RangerPolicyItemAccess> expanded = null;
 
-            item = items[PolicyTermType.ALLOW.ordinal()];
-            if (item != null) {
-                existingPolicy.addPolicyItem(item);
-            }
+                    for (RangerPolicyItemAccess access : 
policyItem.getAccesses()) {
+                        Set<String> implied = 
impliedGrants.get(access.getType());
 
-            item = items[PolicyTermType.DENY.ordinal()];
-            if (item != null) {
-                existingPolicy.addDenyPolicyItem(item);
-            }
+                        if (implied != null && 
!Boolean.FALSE.equals(access.getIsAllowed()) && 
!accessTypesToRevoke.contains(access.getType()) && 
!Collections.disjoint(implied, accessTypesToRevoke)) {
+                            if (expanded == null) {
+                                expanded = new 
ArrayList<>(policyItem.getAccesses());
+                            }
 
-            item = items[PolicyTermType.ALLOW_EXCEPTIONS.ordinal()];
-            if (item != null) {
-                existingPolicy.addAllowException(item);
-            }
+                            expanded.remove(access);

Review Comment:
   Removing Hive's `all` entry also makes the REST authorization delta include 
`all`: `ServiceDefUtil.getExpandedImpliedGrants()` includes the implying access 
type itself, so `RangerPolicyAdminImpl.collectAccessTypes()` compares `{all, 
select, update, ...}` with the remaining concrete privileges. Consequently, a 
grantor delegated only SELECT passes the request check but fails 
`ensureAdminAccess()` when revoking SELECT (or its grant option) from an ALL 
holder. Normalize Hive ALL as a composite in the authorization diff too, so 
this representation change does not require ALL authority.



-- 
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