Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#10412] feat(server-common): Support group-inherited roles in JcasbinAuthorizer (#10868)

Bharath Krishna611038de4885
diff --git a/core/src/main/java/org/apache/gravitino/hook/AccessControlHookDispatcher.java b/core/src/main/java/org/apache/gravitino/hook/AccessControlHookDispatcher.java
index d90601ad8e..2692330962 100644
--- a/core/src/main/java/org/apache/gravitino/hook/AccessControlHookDispatcher.java
+++ b/core/src/main/java/org/apache/gravitino/hook/AccessControlHookDispatcher.java
@@ -129,7 +129,7 @@ public class AccessControlHookDispatcher implements AccessControlDispatcher {
public Group grantRolesToGroup(String metalake, List<String> roles, String group)
throws NoSuchGroupException, IllegalRoleException, NoSuchMetalakeException {
Group grantedGroup = dispatcher.grantRolesToGroup(metalake, roles, group);
- notifyRoleUserRelChange(metalake, roles);
+ notifyRoleGroupRelChange(metalake, roles);
return grantedGroup;
}
@@ -137,7 +137,7 @@ public class AccessControlHookDispatcher implements AccessControlDispatcher {
public Group revokeRolesFromGroup(String metalake, List<String> roles, String group)
throws NoSuchGroupException, IllegalRoleException, NoSuchMetalakeException {
Group revokedGroup = dispatcher.revokeRolesFromGroup(metalake, roles, group);
- notifyRoleUserRelChange(metalake, roles);
+ notifyRoleGroupRelChange(metalake, roles);
return revokedGroup;
}
@@ -258,4 +258,13 @@ public class AccessControlHookDispatcher implements AccessControlDispatcher {
gravitinoAuthorizer.handleRolePrivilegeChange(role);
}
}
+
+ private static void notifyRoleGroupRelChange(String metalake, List<String> roles) {
+ GravitinoAuthorizer gravitinoAuthorizer = GravitinoEnv.getInstance().gravitinoAuthorizer();
+ if (gravitinoAuthorizer != null) {
+ for (String role : roles) {
+ gravitinoAuthorizer.handleRolePrivilegeChange(metalake, role);
+ }
+ }
+ }
}
diff --git a/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinAuthorizer.java b/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinAuthorizer.java
index e675277ab2..2e1f669b8f 100644
--- a/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinAuthorizer.java
+++ b/server-common/src/main/java/org/apache/gravitino/server/authorization/jcasbin/JcasbinAuthorizer.java
@@ -27,9 +27,11 @@ import java.nio.charset.StandardCharsets;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
+import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
@@ -286,7 +288,18 @@ public class JcasbinAuthorizer implements GravitinoAuthorizer {
SupportsRelationOperations.Type.ROLE_USER_REL,
userNameIdentifier,
Entity.EntityType.USER);
- return entities.stream().anyMatch(roleEntity -> Objects.equals(roleEntity.id(), roleId));
+ // Check direct user-role assignment
+ if (entities.stream().anyMatch(roleEntity -> Objects.equals(roleEntity.id(), roleId))) {
+ return true;
+ }
+ // Check group-role assignments.
+ for (GroupEntity groupEntity : resolveCurrentUserGroups(metalake, entityStore)) {
+ List<Long> groupRoleIds = groupEntity.roleIds();
+ if (groupRoleIds != null && groupRoleIds.contains(roleId)) {
+ return true;
+ }
+ }
+ return false;
} catch (Exception e) {
LOG.warn("can not get user id or role id.", e);
@@ -503,41 +516,117 @@ public class JcasbinAuthorizer implements GravitinoAuthorizer {
userNameIdentifier,
Entity.EntityType.USER);
List<CompletableFuture<Void>> loadRoleFutures = new ArrayList<>();
+ Set<String> desiredRoleIds = new HashSet<>();
for (RoleEntity role : entities) {
- Long roleId = role.id();
- allowEnforcer.addRoleForUser(String.valueOf(userId), String.valueOf(roleId));
- denyEnforcer.addRoleForUser(String.valueOf(userId), String.valueOf(roleId));
- if (loadedRoles.getIfPresent(roleId) != null) {
+ desiredRoleIds.add(String.valueOf(role.id()));
+ addRoleForUserAndLoadPolicies(
+ userId, metalake, role.id(), role.name(), loadRoleFutures, entityStore);
+ }
+
+ // Load roles inherited from the user's groups.
+ for (GroupEntity groupEntity : resolveCurrentUserGroups(metalake, entityStore)) {
+ List<Long> roleIds = groupEntity.roleIds();
+ List<String> roleNames = groupEntity.roleNames();
+ if (roleIds == null || roleNames == null) {
+ continue;
+ }
+ if (roleIds.size() != roleNames.size()) {
+ LOG.warn(
+ "Group {} has mismatched roleIds ({}) and roleNames ({}) -- skipping",
+ groupEntity.name(),
+ roleIds.size(),
+ roleNames.size());
continue;
}
- CompletableFuture<Void> loadRoleFuture =
- CompletableFuture.supplyAsync(
- () -> {
- try {
- return entityStore.get(
- NameIdentifierUtil.ofRole(metalake, role.name()),
- Entity.EntityType.ROLE,
- RoleEntity.class);
- } catch (Exception e) {
- throw new RuntimeException("Failed to load role: " + role.name(), e);
- }
- },
- executor)
- .thenAcceptAsync(
- roleEntity -> {
- loadPolicyByRoleEntity(roleEntity);
- loadedRoles.put(roleId, true);
- },
- executor);
- loadRoleFutures.add(loadRoleFuture);
+ for (int i = 0; i < roleIds.size(); i++) {
+ desiredRoleIds.add(String.valueOf(roleIds.get(i)));
+ addRoleForUserAndLoadPolicies(
+ userId,
+ metalake,
+ roleIds.get(i),
+ roleNames.get(i),
+ loadRoleFutures,
+ entityStore);
+ }
}
+
CompletableFuture.allOf(loadRoleFutures.toArray(new CompletableFuture[0])).join();
+
+ // Prune stale g-rows: remove role mappings that are no longer valid
+ // (e.g. user was removed from a group at the IdP level).
+ String userIdStr = String.valueOf(userId);
+ for (String currentRole : allowEnforcer.getRolesForUser(userIdStr)) {
+ if (!desiredRoleIds.contains(currentRole)) {
+ allowEnforcer.deleteRoleForUser(userIdStr, currentRole);
+ denyEnforcer.deleteRoleForUser(userIdStr, currentRole);
+ }
+ }
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
+ /**
+ * Resolves GroupEntity objects for the current principal's groups, skipping any that are stale or
+ * not found in the store.
+ */
+ private List<GroupEntity> resolveCurrentUserGroups(String metalake, EntityStore entityStore) {
+ Principal principal = PrincipalUtils.getCurrentPrincipal();
+ if (!(principal instanceof UserPrincipal)) {
+ return new ArrayList<>();
+ }
+ List<UserGroup> groups = ((UserPrincipal) principal).getGroups();
+ if (groups.isEmpty()) {
+ return new ArrayList<>();
+ }
+ List<NameIdentifier> groupIdents =
+ groups.stream()
+ .map(g -> NameIdentifierUtil.ofGroup(metalake, g.getGroupname()))
+ .collect(Collectors.toList());
+ return entityStore.batchGet(groupIdents, Entity.EntityType.GROUP, GroupEntity.class);
+ }
+
+ /**
+ * Adds a role mapping for the given user in both enforcers and asynchronously loads the role's
+ * policies if they are not already cached. When a role needs loading, the resulting {@link
+ * CompletableFuture} is appended to {@code loadRoleFutures} so the caller can join all futures
+ * after processing both direct and group-inherited roles.
+ */
+ private void addRoleForUserAndLoadPolicies(
+ Long userId,
+ String metalake,
+ Long roleId,
+ String roleName,
+ List<CompletableFuture<Void>> loadRoleFutures,
+ EntityStore entityStore) {
+ allowEnforcer.addRoleForUser(String.valueOf(userId), String.valueOf(roleId));
+ denyEnforcer.addRoleForUser(String.valueOf(userId), String.valueOf(roleId));
+ if (loadedRoles.getIfPresent(roleId) != null) {
+ return;
+ }
+ CompletableFuture<Void> loadRoleFuture =
+ CompletableFuture.supplyAsync(
+ () -> {
+ try {
+ return entityStore.get(
+ NameIdentifierUtil.ofRole(metalake, roleName),
+ Entity.EntityType.ROLE,
+ RoleEntity.class);
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to load role: " + roleName, e);
+ }
+ },
+ executor)
+ .thenAcceptAsync(
+ roleEntity -> {
+ loadPolicyByRoleEntity(roleEntity);
+ loadedRoles.put(roleId, true);
+ },
+ executor);
+ loadRoleFutures.add(loadRoleFuture);
+ }
+
private void loadOwnerPolicy(String metalake, MetadataObject metadataObject, Long metadataId) {
if (ownerRel.getIfPresent(metadataId) != null) {
LOG.debug("Metadata {} OWNER has been loaded.", metadataId);
diff --git a/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizer.java b/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizer.java
index fb925cc915..afa48efc98 100644
--- a/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizer.java
+++ b/server-common/src/test/java/org/apache/gravitino/server/authorization/jcasbin/TestJcasbinAuthorizer.java
@@ -74,6 +74,7 @@ import org.apache.gravitino.utils.PrincipalUtils;
import org.casbin.jcasbin.main.Enforcer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
@@ -131,6 +132,7 @@ public class TestJcasbinAuthorizer {
.when(PrincipalUtils::getCurrentPrincipal)
.thenReturn(new UserPrincipal(USERNAME));
principalUtilsMockedStatic.when(() -> PrincipalUtils.doAs(any(), any())).thenCallRealMethod();
+ principalUtilsMockedStatic.when(PrincipalUtils::getCurrentUserName).thenCallRealMethod();
metadataIdConverterMockedStatic
.when(() -> MetadataIdConverter.getID(any(), eq(METALAKE)))
.thenReturn(CATALOG_ID);
@@ -173,6 +175,21 @@ public class TestJcasbinAuthorizer {
}
}
+ @BeforeEach
+ public void resetSharedState() throws Exception {
+ // Reset shared enforcer and cache state to prevent test ordering contamination.
+ getLoadedRolesCache(jcasbinAuthorizer).invalidateAll();
+ restoreDefaultPrincipal();
+ // Reset role-user relation mock to return empty list (no roles) by default; individual tests
+ // can override as needed.
+ NameIdentifier userNameIdentifier = NameIdentifierUtil.ofUser(METALAKE, USERNAME);
+ when(supportsRelationOperations.listEntitiesByRelation(
+ eq(SupportsRelationOperations.Type.ROLE_USER_REL),
+ eq(userNameIdentifier),
+ eq(Entity.EntityType.USER)))
+ .thenReturn(ImmutableList.of());
+ }
+
@Test
public void testAuthorize() throws Exception {
makeCompletableFutureUseCurrentThread(jcasbinAuthorizer);
@@ -194,8 +211,8 @@ public class TestJcasbinAuthorizer {
.thenReturn(ImmutableList.of(allowRole));
assertTrue(doAuthorize(currentPrincipal));
// Test role cache.
- // When permissions are changed but handleRolePrivilegeChange is not executed, the system will
- // use the cached permissions in JCasbin, so authorize can succeed.
+ // When the user's role changes to one with no privileges, the prune step removes
+ // the stale role's g-rows from the enforcer, so authorization fails immediately.
Long newRoleId = -1L;
RoleEntity tempNewRole = getRoleEntity(newRoleId, "tempNewRole", ImmutableList.of());
when(entityStore.get(
@@ -208,10 +225,7 @@ public class TestJcasbinAuthorizer {
eq(userNameIdentifier),
eq(Entity.EntityType.USER)))
.thenReturn(ImmutableList.of(tempNewRole));
- assertTrue(doAuthorize(currentPrincipal));
- // After clearing the cache, authorize will fail
- jcasbinAuthorizer.handleRolePrivilegeChange(ALLOW_ROLE_ID);
- // assertFalse(doAuthorize(currentPrincipal));
+ assertFalse(doAuthorize(currentPrincipal));
// When the user is re-assigned the correct role, the authorization will succeed.
when(supportsRelationOperations.listEntitiesByRelation(
eq(SupportsRelationOperations.Type.ROLE_USER_REL),
@@ -344,6 +358,500 @@ public class TestJcasbinAuthorizer {
.thenReturn(new UserPrincipal(USERNAME));
}
+ @Test
+ public void testAuthorizeByGroupRole() throws Exception {
+ makeCompletableFutureUseCurrentThread(jcasbinAuthorizer);
+
+ UserPrincipal groupPrincipal = setCurrentPrincipalWithGroup(GROUP_NAME);
+
+ // Create a role with USE_CATALOG privilege
+ Long groupRoleId = 7L;
+ RoleEntity groupRole =
+ mockRoleInStore(groupRoleId, "groupRole", ImmutableList.of(getAllowSecurableObject()));
+
+ mockNoDirectUserRoles();
+ mockGroupWithRoles(
+ GROUP_NAME, ImmutableList.of(groupRoleId), ImmutableList.of(groupRole.name()));
+
+ // Authorization should succeed via group-inherited role
+ assertTrue(doAuthorize(groupPrincipal));
+
+ // A principal with no groups should fail
+ UserPrincipal noGroupPrincipal = setCurrentPrincipalWithGroup(null);
+ // Clear role caches to force re-evaluation
+ getLoadedRolesCache(jcasbinAuthorizer).invalidateAll();
+ assertFalse(doAuthorize(noGroupPrincipal));
+
+ restoreDefaultPrincipal();
+ }
+
+ @Test
+ public void testAuthorizeByDirectAndGroupRoles() throws Exception {
+ makeCompletableFutureUseCurrentThread(jcasbinAuthorizer);
+ getLoadedRolesCache(jcasbinAuthorizer).invalidateAll();
+
+ UserPrincipal groupPrincipal = setCurrentPrincipalWithGroup(GROUP_NAME);
+
+ // Direct role has no privilege; group role grants USE_CATALOG
+ Long directRoleId = 8L;
+ RoleEntity directRole = mockRoleInStore(directRoleId, "directRole", ImmutableList.of());
+ Long groupRoleId = 9L;
+ RoleEntity groupRole =
+ mockRoleInStore(
+ groupRoleId, "groupCatalogRole", ImmutableList.of(getAllowSecurableObject()));
+
+ NameIdentifier userNameIdentifier = NameIdentifierUtil.ofUser(METALAKE, USERNAME);
+ when(supportsRelationOperations.listEntitiesByRelation(
+ eq(SupportsRelationOperations.Type.ROLE_USER_REL),
+ eq(userNameIdentifier),
+ eq(Entity.EntityType.USER)))
+ .thenReturn(ImmutableList.of(directRole));
+
+ mockGroupWithRoles(
+ GROUP_NAME, ImmutableList.of(groupRoleId), ImmutableList.of(groupRole.name()));
+
+ // Authorization should succeed -- direct role has no privilege, but group role does
+ assertTrue(doAuthorize(groupPrincipal));
+
+ restoreDefaultPrincipal();
+ getLoadedRolesCache(jcasbinAuthorizer).invalidateAll();
+ }
+
+ @Test
+ public void testIsSelfRoleViaGroup() throws Exception {
+ // Use a role whose MetadataIdConverter.getID resolves to CATALOG_ID (catch-all mock)
+ Long groupRoleId = CATALOG_ID;
+ String groupRoleName = "groupSelfRole";
+ NameIdentifier roleIdent = NameIdentifierUtil.ofRole(METALAKE, groupRoleName);
+
+ mockNoDirectUserRoles();
+ setCurrentPrincipalWithGroup(GROUP_NAME);
+ mockGroupWithRoles(GROUP_NAME, ImmutableList.of(groupRoleId), ImmutableList.of(groupRoleName));
+
+ // isSelf should return true -- role is assigned to user's group
+ assertTrue(jcasbinAuthorizer.isSelf(Entity.EntityType.ROLE, roleIdent));
+
+ // A principal with no groups should fail
+ setCurrentPrincipalWithGroup(null);
+ assertFalse(jcasbinAuthorizer.isSelf(Entity.EntityType.ROLE, roleIdent));
+
+ restoreDefaultPrincipal();
+ }
+
+ @Test
+ public void testGroupRoleSkippedWhenRoleIdsAndNamesMismatch() throws Exception {
+ makeCompletableFutureUseCurrentThread(jcasbinAuthorizer);
+ getLoadedRolesCache(jcasbinAuthorizer).invalidateAll();
+
+ String mismatchGroupName = "mismatchGroup";
+ UserPrincipal groupPrincipal = setCurrentPrincipalWithGroup(mismatchGroupName);
+
+ mockNoDirectUserRoles();
+ // Mismatched roleIds (1) and roleNames (2) -- the whole group should be skipped
+ mockGroupWithRoles(
+ mismatchGroupName, ImmutableList.of(101L), ImmutableList.of("roleA", "roleB"));
+
+ // Authorization denied -- the mismatched group is skipped, so no role is loaded
+ assertFalse(doAuthorize(groupPrincipal));
+
+ restoreDefaultPrincipal();
+ getLoadedRolesCache(jcasbinAuthorizer).invalidateAll();
+ }
+
+ @Test
+ public void testStaleGroupSkippedWhenNotInStore() throws Exception {
+ makeCompletableFutureUseCurrentThread(jcasbinAuthorizer);
+ getLoadedRolesCache(jcasbinAuthorizer).invalidateAll();
+
+ String staleGroupName = "staleGroup";
+ UserPrincipal groupPrincipal = setCurrentPrincipalWithGroup(staleGroupName);
+
+ mockNoDirectUserRoles();
+ // batchGet silently skips missing entities -- the stale group returns an empty list
+ when(entityStore.batchGet(
+ eq(ImmutableList.of(NameIdentifierUtil.ofGroup(METALAKE, staleGroupName))),
+ eq(Entity.EntityType.GROUP),
+ eq(GroupEntity.class)))
+ .thenReturn(ImmutableList.of());
+
+ // Authorization denied without throwing -- the stale group is silently skipped
+ assertFalse(doAuthorize(groupPrincipal));
+
+ restoreDefaultPrincipal();
+ getLoadedRolesCache(jcasbinAuthorizer).invalidateAll();
+ }
+
+ @Test
+ public void testGroupRoleRevokedDeniesAccess() throws Exception {
+ makeCompletableFutureUseCurrentThread(jcasbinAuthorizer);
+ getLoadedRolesCache(jcasbinAuthorizer).invalidateAll();
+
+ UserPrincipal groupPrincipal = setCurrentPrincipalWithGroup(GROUP_NAME);
+
+ // Group has a role that grants USE_CATALOG
+ Long groupRoleId = 10L;
+ RoleEntity groupRole =
+ mockRoleInStore(groupRoleId, "revokableRole", ImmutableList.of(getAllowSecurableObject()));
+
+ mockNoDirectUserRoles();
+ mockGroupWithRoles(
+ GROUP_NAME, ImmutableList.of(groupRoleId), ImmutableList.of(groupRole.name()));
+
+ // Authorization succeeds via group-inherited role
+ assertTrue(doAuthorize(groupPrincipal));
+
+ // Simulate group removing the role: invalidate the cache (same as handleRolePrivilegeChange)
+ // and update the group mock to have no roles
+ mockGroupWithRoles(GROUP_NAME, ImmutableList.of(), ImmutableList.of());
+ jcasbinAuthorizer.handleRolePrivilegeChange(groupRoleId);
+
+ // Authorization should now be denied -- the role was removed from the group
+ assertFalse(doAuthorize(groupPrincipal));
+
+ restoreDefaultPrincipal();
+ getLoadedRolesCache(jcasbinAuthorizer).invalidateAll();
+ }
+
+ @Test
+ public void testRoleSharedByUserAndGroupSurvivesGroupRevocation() throws Exception {
+ makeCompletableFutureUseCurrentThread(jcasbinAuthorizer);
+ getLoadedRolesCache(jcasbinAuthorizer).invalidateAll();
+
+ UserPrincipal groupPrincipal = setCurrentPrincipalWithGroup(GROUP_NAME);
+
+ // The same role is assigned both directly to the user AND to the user's group
+ Long sharedRoleId = 11L;
+ RoleEntity sharedRole =
+ mockRoleInStore(sharedRoleId, "sharedRole", ImmutableList.of(getAllowSecurableObject()));
+
+ NameIdentifier userNameIdentifier = NameIdentifierUtil.ofUser(METALAKE, USERNAME);
+ when(supportsRelationOperations.listEntitiesByRelation(
+ eq(SupportsRelationOperations.Type.ROLE_USER_REL),
+ eq(userNameIdentifier),
+ eq(Entity.EntityType.USER)))
+ .thenReturn(ImmutableList.of(sharedRole));
+ mockGroupWithRoles(
+ GROUP_NAME, ImmutableList.of(sharedRoleId), ImmutableList.of(sharedRole.name()));
+
+ // Authorization succeeds (role via both direct and group)
+ assertTrue(doAuthorize(groupPrincipal));
+
+ // Group removes the role; user still has it directly
+ mockGroupWithRoles(GROUP_NAME, ImmutableList.of(), ImmutableList.of());
+ jcasbinAuthorizer.handleRolePrivilegeChange(sharedRoleId);
+
+ // Authorization should still succeed -- role is retained via direct assignment
+ assertTrue(doAuthorize(groupPrincipal));
+
+ restoreDefaultPrincipal();
+ getLoadedRolesCache(jcasbinAuthorizer).invalidateAll();
+ }
+
+ /**
+ * Inverse of {@link #testRoleSharedByUserAndGroupSurvivesGroupRevocation}: the same role is
+ * assigned to both the user directly AND the user's group. When the role is revoked from the
+ * user, the group still has it. Access should survive via group inheritance.
+ */
+ @Test
+ public void testRoleSharedByUserAndGroupSurvivesUserRevocation() throws Exception {
+ makeCompletableFutureUseCurrentThread(jcasbinAuthorizer);
+ getLoadedRolesCache(jcasbinAuthorizer).invalidateAll();
+
+ UserPrincipal groupPrincipal = setCurrentPrincipalWithGroup(GROUP_NAME);
+
+ // The same role is assigned both directly to the user AND to the user's group
+ Long sharedRoleId = 12L;
+ RoleEntity sharedRole =
+ mockRoleInStore(
+ sharedRoleId, "sharedRoleForUserRevoke", ImmutableList.of(getAllowSecurableObject()));
+
+ NameIdentifier userNameIdentifier = NameIdentifierUtil.ofUser(METALAKE, USERNAME);
+ when(supportsRelationOperations.listEntitiesByRelation(
+ eq(SupportsRelationOperations.Type.ROLE_USER_REL),
+ eq(userNameIdentifier),
+ eq(Entity.EntityType.USER)))
+ .thenReturn(ImmutableList.of(sharedRole));
+ mockGroupWithRoles(
+ GROUP_NAME, ImmutableList.of(sharedRoleId), ImmutableList.of(sharedRole.name()));
+
+ // Authorization succeeds (role via both direct and group)
+ assertTrue(doAuthorize(groupPrincipal));
+
+ // User loses the role directly; group still has it
+ when(supportsRelationOperations.listEntitiesByRelation(
+ eq(SupportsRelationOperations.Type.ROLE_USER_REL),
+ eq(userNameIdentifier),
+ eq(Entity.EntityType.USER)))
+ .thenReturn(ImmutableList.of());
+ jcasbinAuthorizer.handleRolePrivilegeChange(sharedRoleId);
+
+ // Authorization should still succeed -- role is retained via group inheritance
+ assertTrue(doAuthorize(groupPrincipal));
+
+ restoreDefaultPrincipal();
+ getLoadedRolesCache(jcasbinAuthorizer).invalidateAll();
+ }
+
+ /**
+ * When the user is removed from a group at the IdP level (e.g. Azure AD), the next JWT token
+ * won't include that group. On the next request the group's roles should no longer be available.
+ */
+ @Test
+ public void testUserRemovedFromGroupAtIdpDeniesAccess() throws Exception {
+ makeCompletableFutureUseCurrentThread(jcasbinAuthorizer);
+ getLoadedRolesCache(jcasbinAuthorizer).invalidateAll();
+
+ UserPrincipal groupPrincipal = setCurrentPrincipalWithGroup(GROUP_NAME);
+
+ // Group has a role that grants USE_CATALOG; user has no direct roles
+ Long groupRoleId = 13L;
+ RoleEntity groupRole =
+ mockRoleInStore(groupRoleId, "idpGroupRole", ImmutableList.of(getAllowSecurableObject()));
+
+ mockNoDirectUserRoles();
+ mockGroupWithRoles(
+ GROUP_NAME, ImmutableList.of(groupRoleId), ImmutableList.of(groupRole.name()));
+
+ // Authorization succeeds via group-inherited role
+ assertTrue(doAuthorize(groupPrincipal));
+
+ // User is removed from the group at the IdP level -- next token has no groups.
+ UserPrincipal noGroupPrincipal = setCurrentPrincipalWithGroup(null);
+
+ // The prune step detects that the group-inherited role is no longer valid
+ // (group not in token → role not in desiredRoleIds) and removes the stale g-rows.
+ // Access is denied immediately without waiting for cache TTL expiry.
+ assertFalse(doAuthorize(noGroupPrincipal));
+
+ restoreDefaultPrincipal();
+ getLoadedRolesCache(jcasbinAuthorizer).invalidateAll();
+ }
+
+ /**
+ * When a user belongs to multiple groups and one group's role is revoked, roles from the other
+ * group should still grant access.
+ */
+ @Test
+ public void testMultipleGroupsPartialRevocationRetainsAccess() throws Exception {
+ makeCompletableFutureUseCurrentThread(jcasbinAuthorizer);
+ getLoadedRolesCache(jcasbinAuthorizer).invalidateAll();
+
+ String groupA = "groupA";
+ String groupB = "groupB";
+ Long groupAId = 14L;
+ Long groupBId = 15L;
+
+ // Principal belongs to two groups
+ UserPrincipal multiGroupPrincipal =
+ new UserPrincipal(
+ USERNAME,
+ ImmutableList.of(
+ new UserGroup(Optional.empty(), groupA), new UserGroup(Optional.empty(), groupB)));
+ principalUtilsMockedStatic
+ .when(PrincipalUtils::getCurrentPrincipal)
+ .thenReturn(multiGroupPrincipal);
+
+ // Group A has a role with USE_CATALOG; Group B has a different role also with USE_CATALOG
+ Long roleAId = 16L;
+ Long roleBId = 17L;
+ RoleEntity roleA =
+ mockRoleInStore(roleAId, "roleA", ImmutableList.of(getAllowSecurableObject()));
+ RoleEntity roleB =
+ mockRoleInStore(roleBId, "roleB", ImmutableList.of(getAllowSecurableObject()));
+
+ mockNoDirectUserRoles();
+
+ GroupEntity groupAEntity =
+ GroupEntity.builder()
+ .withId(groupAId)
+ .withName(groupA)
+ .withNamespace(Namespace.of(METALAKE, "group"))
+ .withAuditInfo(AuditInfo.EMPTY)
+ .withRoleNames(ImmutableList.of(roleA.name()))
+ .withRoleIds(ImmutableList.of(roleAId))
+ .build();
+ GroupEntity groupBEntity =
+ GroupEntity.builder()
+ .withId(groupBId)
+ .withName(groupB)
+ .withNamespace(Namespace.of(METALAKE, "group"))
+ .withAuditInfo(AuditInfo.EMPTY)
+ .withRoleNames(ImmutableList.of(roleB.name()))
+ .withRoleIds(ImmutableList.of(roleBId))
+ .build();
+ when(entityStore.batchGet(
+ eq(
+ ImmutableList.of(
+ NameIdentifierUtil.ofGroup(METALAKE, groupA),
+ NameIdentifierUtil.ofGroup(METALAKE, groupB))),
+ eq(Entity.EntityType.GROUP),
+ eq(GroupEntity.class)))
+ .thenReturn(ImmutableList.of(groupAEntity, groupBEntity));
+
+ // Authorization succeeds
+ assertTrue(doAuthorize(multiGroupPrincipal));
+
+ // Revoke roleA from groupA; groupB still has roleB
+ GroupEntity groupANoRoles =
+ GroupEntity.builder()
+ .withId(groupAId)
+ .withName(groupA)
+ .withNamespace(Namespace.of(METALAKE, "group"))
+ .withAuditInfo(AuditInfo.EMPTY)
+ .withRoleNames(ImmutableList.of())
+ .withRoleIds(ImmutableList.of())
+ .build();
+ when(entityStore.batchGet(
+ eq(
+ ImmutableList.of(
+ NameIdentifierUtil.ofGroup(METALAKE, groupA),
+ NameIdentifierUtil.ofGroup(METALAKE, groupB))),
+ eq(Entity.EntityType.GROUP),
+ eq(GroupEntity.class)))
+ .thenReturn(ImmutableList.of(groupANoRoles, groupBEntity));
+ jcasbinAuthorizer.handleRolePrivilegeChange(roleAId);
+
+ // Authorization should still succeed via groupB's role
+ assertTrue(doAuthorize(multiGroupPrincipal));
+
+ restoreDefaultPrincipal();
+ getLoadedRolesCache(jcasbinAuthorizer).invalidateAll();
+ }
+
+ /**
+ * When a group grants an ALLOW privilege and a user has a direct DENY on the same resource, the
+ * deny should take precedence (deny wins over allow).
+ */
+ @Test
+ public void testDenyRoleOnUserOverridesAllowFromGroup() throws Exception {
+ makeCompletableFutureUseCurrentThread(jcasbinAuthorizer);
+ getLoadedRolesCache(jcasbinAuthorizer).invalidateAll();
+
+ UserPrincipal groupPrincipal = setCurrentPrincipalWithGroup(GROUP_NAME);
+
+ // Group has an allow role
+ Long allowRoleId = 18L;
+ RoleEntity allowRole =
+ mockRoleInStore(allowRoleId, "groupAllowRole", ImmutableList.of(getAllowSecurableObject()));
+ mockGroupWithRoles(
+ GROUP_NAME, ImmutableList.of(allowRoleId), ImmutableList.of(allowRole.name()));
+
+ // User has a deny role directly
+ Long denyRoleId = 19L;
+ RoleEntity denyRole =
+ mockRoleInStore(denyRoleId, "userDenyRole", ImmutableList.of(getDenySecurableObject()));
+ NameIdentifier userNameIdentifier = NameIdentifierUtil.ofUser(METALAKE, USERNAME);
+ when(supportsRelationOperations.listEntitiesByRelation(
+ eq(SupportsRelationOperations.Type.ROLE_USER_REL),
+ eq(userNameIdentifier),
+ eq(Entity.EntityType.USER)))
+ .thenReturn(ImmutableList.of(denyRole));
+
+ // Deny should win -- user has explicit deny even though group provides allow
+ assertFalse(doAuthorize(groupPrincipal));
+
+ restoreDefaultPrincipal();
+ getLoadedRolesCache(jcasbinAuthorizer).invalidateAll();
+ }
+
+ /** Inverse: group has a DENY role while user has a direct ALLOW role. Deny should still win. */
+ @Test
+ public void testDenyRoleFromGroupOverridesAllowOnUser() throws Exception {
+ makeCompletableFutureUseCurrentThread(jcasbinAuthorizer);
+ getLoadedRolesCache(jcasbinAuthorizer).invalidateAll();
+
+ UserPrincipal groupPrincipal = setCurrentPrincipalWithGroup(GROUP_NAME);
+
+ // Group has a deny role
+ Long denyRoleId = 20L;
+ RoleEntity denyRole =
+ mockRoleInStore(denyRoleId, "groupDenyRole", ImmutableList.of(getDenySecurableObject()));
+ mockGroupWithRoles(GROUP_NAME, ImmutableList.of(denyRoleId), ImmutableList.of(denyRole.name()));
+
+ // User has an allow role directly
+ Long allowRoleId = 21L;
+ RoleEntity allowRole =
+ mockRoleInStore(allowRoleId, "userAllowRole", ImmutableList.of(getAllowSecurableObject()));
+ NameIdentifier userNameIdentifier = NameIdentifierUtil.ofUser(METALAKE, USERNAME);
+ when(supportsRelationOperations.listEntitiesByRelation(
+ eq(SupportsRelationOperations.Type.ROLE_USER_REL),
+ eq(userNameIdentifier),
+ eq(Entity.EntityType.USER)))
+ .thenReturn(ImmutableList.of(allowRole));
+
+ // Deny should win -- group provides deny even though user has direct allow
+ assertFalse(doAuthorize(groupPrincipal));
+
+ restoreDefaultPrincipal();
+ getLoadedRolesCache(jcasbinAuthorizer).invalidateAll();
+ }
+
+ /**
+ * Sets the current principal mock to a {@link UserPrincipal} with the given group, or with no
+ * groups when {@code groupName} is null. Returns the principal for use in assertions.
+ */
+ private static UserPrincipal setCurrentPrincipalWithGroup(String groupName) {
+ UserPrincipal principal =
+ groupName == null
+ ? new UserPrincipal(USERNAME)
+ : new UserPrincipal(
+ USERNAME, ImmutableList.of(new UserGroup(Optional.empty(), groupName)));
+ principalUtilsMockedStatic.when(PrincipalUtils::getCurrentPrincipal).thenReturn(principal);
+ return principal;
+ }
+
+ /** Restores the default principal mock used by other tests. */
+ private static void restoreDefaultPrincipal() {
+ principalUtilsMockedStatic
+ .when(PrincipalUtils::getCurrentPrincipal)
+ .thenReturn(new UserPrincipal(USERNAME));
+ }
+
+ /** Mocks the user as having no direct (ROLE_USER_REL) role assignments. */
+ private static void mockNoDirectUserRoles() throws IOException {
+ NameIdentifier userNameIdentifier = NameIdentifierUtil.ofUser(METALAKE, USERNAME);
+ when(supportsRelationOperations.listEntitiesByRelation(
+ eq(SupportsRelationOperations.Type.ROLE_USER_REL),
+ eq(userNameIdentifier),
+ eq(Entity.EntityType.USER)))
+ .thenReturn(ImmutableList.of());
+ }
+
+ /** Builds a {@link RoleEntity} and registers it in the mocked entity store. */
+ private static RoleEntity mockRoleInStore(
+ Long roleId, String roleName, List<SecurableObject> securableObjects) throws IOException {
+ RoleEntity role = getRoleEntity(roleId, roleName, securableObjects);
+ when(entityStore.get(
+ eq(NameIdentifierUtil.ofRole(METALAKE, roleName)),
+ eq(Entity.EntityType.ROLE),
+ eq(RoleEntity.class)))
+ .thenReturn(role);
+ return role;
+ }
+
+ /**
+ * Builds a {@link GroupEntity} with the given role ids/names and registers it in the mocked
+ * entity store via batchGet.
+ */
+ private static GroupEntity mockGroupWithRoles(
+ String groupName, List<Long> roleIds, List<String> roleNames) throws IOException {
+ GroupEntity group =
+ GroupEntity.builder()
+ .withId(GROUP_ID)
+ .withName(groupName)
+ .withNamespace(Namespace.of(METALAKE, "group"))
+ .withAuditInfo(AuditInfo.EMPTY)
+ .withRoleNames(roleNames)
+ .withRoleIds(roleIds)
+ .build();
+ when(entityStore.batchGet(
+ eq(ImmutableList.of(NameIdentifierUtil.ofGroup(METALAKE, groupName))),
+ eq(Entity.EntityType.GROUP),
+ eq(GroupEntity.class)))
+ .thenReturn(ImmutableList.of(group));
+ return group;
+ }
+
private Boolean doAuthorize(Principal currentPrincipal) {
return jcasbinAuthorizer.authorize(
currentPrincipal,