World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#2237] feat(core): Add the support of PermissionManager (#2958)
qqqttt123ec3b6c4f6af3
diff --git a/core/src/main/java/com/datastrato/gravitino/Configs.java b/core/src/main/java/com/datastrato/gravitino/Configs.javaindex 9037376087..4d361f4343 100644--- a/core/src/main/java/com/datastrato/gravitino/Configs.java+++ b/core/src/main/java/com/datastrato/gravitino/Configs.java@@ -256,4 +256,11 @@ public interface Configs {.checkValue(StringUtils::isNotBlank, ConfigConstants.NOT_BLANK_ERROR_MSG).toSequence().create();++ ConfigEntry<Long> ROLE_CACHE_EVICTION_INTERVAL_MS =+ new ConfigBuilder("gravitino.authorization.roleCacheEvictionIntervalMs")+ .doc("The interval in milliseconds to evict the role cache")+ .version(ConfigConstants.VERSION_0_5_0)+ .longConf()+ .createWithDefault(60 * 60 * 1000L);}diff --git a/core/src/main/java/com/datastrato/gravitino/GravitinoEnv.java b/core/src/main/java/com/datastrato/gravitino/GravitinoEnv.javaindex 57c3ea18bc..cbc11ca53e 100644--- a/core/src/main/java/com/datastrato/gravitino/GravitinoEnv.java+++ b/core/src/main/java/com/datastrato/gravitino/GravitinoEnv.java@@ -101,7 +101,7 @@ public class GravitinoEnv {/*** This method is used for testing purposes only to set the access manager for test in package- * `com.datastrato.gravitino.server.web.rest`.+ * `com.datastrato.gravitino.server.web.rest` and `com.datastrato.gravitino.authorization`.** @param accessControlManager The access control manager to be set.*/@@ -110,6 +110,17 @@ public class GravitinoEnv {this.accessControlManager = accessControlManager;}+ /**+ * This method is used for testing purposes only to set the entity store for test in package+ * `com.datastrato.gravitino.authorization`.+ *+ * @param entityStore The entity store to be set.+ */+ @VisibleForTesting+ public void setEntityStore(EntityStore entityStore) {+ this.entityStore = entityStore;+ }+/*** Initialize the Gravitino environment.*diff --git a/core/src/main/java/com/datastrato/gravitino/authorization/AccessControlManager.java b/core/src/main/java/com/datastrato/gravitino/authorization/AccessControlManager.javaindex fcfc911d88..131153f451 100644--- a/core/src/main/java/com/datastrato/gravitino/authorization/AccessControlManager.java+++ b/core/src/main/java/com/datastrato/gravitino/authorization/AccessControlManager.java@@ -14,6 +14,7 @@ import com.datastrato.gravitino.exceptions.RoleAlreadyExistsException;import com.datastrato.gravitino.exceptions.UserAlreadyExistsException;import com.datastrato.gravitino.storage.IdGenerator;import com.datastrato.gravitino.utils.Executable;+import com.google.common.annotations.VisibleForTesting;import java.util.List;import java.util.Map;@@ -30,13 +31,15 @@ public class AccessControlManager {private final UserGroupManager userGroupManager;private final AdminManager adminManager;private final RoleManager roleManager;+ private final PermissionManager permissionManager;private final Object adminOperationLock = new Object();private final Object nonAdminOperationLock = new Object();public AccessControlManager(EntityStore store, IdGenerator idGenerator, Config config) {- this.userGroupManager = new UserGroupManager(store, idGenerator);this.adminManager = new AdminManager(store, idGenerator, config);- this.roleManager = new RoleManager(store, idGenerator);+ this.roleManager = new RoleManager(store, idGenerator, config);+ this.userGroupManager = new UserGroupManager(store, idGenerator, roleManager);+ this.permissionManager = new PermissionManager(store, roleManager);}/**@@ -106,7 +109,7 @@ public class AccessControlManager {* Gets a Group.** @param metalake The Metalake of the Group.- * @param group THe name of the Group.+ * @param group The name of the Group.* @return The getting Group instance.* @throws NoSuchGroupException If the Group with the given identifier does not exist.* @throws RuntimeException If getting the Group encounters storage issues.@@ -115,6 +118,70 @@ public class AccessControlManager {return doWithNonAdminLock(() -> userGroupManager.getGroup(metalake, group));}+ /**+ * Grant a role to a user.+ *+ * @param metalake The metalake of the User.+ * @param user The name of the User.+ * @return true` if the User was successfully granted, `false` otherwise.+ * @throws NoSuchUserException If the User with the given identifier does not exist.+ * @throws NoSuchRoleException If the Role with the given identifier does not exist.+ * @throws RoleAlreadyExistsException If the Role with the given identifier already exists in the+ * User.+ * @throws RuntimeException If granting a role to a user encounters storage issues.+ */+ public boolean grantRoleToUser(String metalake, String role, String user) {+ return doWithNonAdminLock(() -> permissionManager.grantRoleToUser(metalake, role, user));+ }++ /**+ * Grant a role to a group.+ *+ * @param metalake The metalake of the Group.+ * @param group THe name of the Group.+ * @return true` if the Group was successfully granted, `false` otherwise.+ * @throws NoSuchGroupException If the Group with the given identifier does not exist.+ * @throws NoSuchRoleException If the Role with the given identifier does not exist.+ * @throws RoleAlreadyExistsException If the Role with the given identifier already exists in the+ * Group.+ * @throws RuntimeException If granting a role to a group encounters storage issues.+ */+ public boolean grantRoleToGroup(String metalake, String role, String group) {+ return doWithNonAdminLock(() -> permissionManager.grantRoleToGroup(metalake, role, group));+ }++ /**+ * Revoke a role from a group.+ *+ * @param metalake The metalake of the Group.+ * @param group The name of the Group.+ * @return true` if the Group was successfully revoked, `false` otherwise.+ * @throws NoSuchGroupException If the Group with the given identifier does not exist.+ * @throws NoSuchRoleException If the Role with the given identifier does not exist.+ * @throws RoleAlreadyExistsException If the Role with the given identifier already exists in the+ * Group.+ * @throws RuntimeException If revoking a role from a group encounters storage issues.+ */+ public boolean revokeRoleFromGroup(String metalake, String role, String group) {+ return doWithNonAdminLock(() -> permissionManager.revokeRoleFromGroup(metalake, role, group));+ }++ /**+ * Revoke a role from a user.+ *+ * @param metalake The metalake of the User.+ * @param user The name of the User.+ * @return true` if the User was successfully revoked, `false` otherwise.+ * @throws NoSuchUserException If the User with the given identifier does not exist.+ * @throws NoSuchRoleException If the Role with the given identifier does not exist.+ * @throws RoleAlreadyExistsException If the Role with the given identifier already exists in the+ * User.+ * @throws RuntimeException If revoking a role from a user encounters storage issues.+ */+ public boolean revokeRoleFromUser(String metalake, String role, String user) {+ return doWithNonAdminLock(() -> permissionManager.revokeRoleFromUser(metalake, role, user));+ }+/*** Adds a new metalake admin.*@@ -206,6 +273,11 @@ public class AccessControlManager {return doWithNonAdminLock(() -> roleManager.dropRole(metalake, role));}+ @VisibleForTesting+ RoleManager getRoleManager() {+ return roleManager;+ }+private <R, E extends Exception> R doWithNonAdminLock(Executable<R, E> executable) throws E {synchronized (nonAdminOperationLock) {return executable.execute();diff --git a/core/src/main/java/com/datastrato/gravitino/authorization/AdminManager.java b/core/src/main/java/com/datastrato/gravitino/authorization/AdminManager.javaindex edbe18cc2c..74ee905402 100644--- a/core/src/main/java/com/datastrato/gravitino/authorization/AdminManager.java+++ b/core/src/main/java/com/datastrato/gravitino/authorization/AdminManager.java@@ -38,21 +38,13 @@ class AdminManager {private final IdGenerator idGenerator;private final List<String> serviceAdmins;- public AdminManager(EntityStore store, IdGenerator idGenerator, Config config) {+ AdminManager(EntityStore store, IdGenerator idGenerator, Config config) {this.store = store;this.idGenerator = idGenerator;this.serviceAdmins = config.get(Configs.SERVICE_ADMINS);}- /**- * Adds a new metalake admin.- *- * @param user The name of the User.- * @return The added User instance.- * @throws UserAlreadyExistsException If a User with the same identifier already exists.- * @throws RuntimeException If adding the User encounters storage issues.- */- public User addMetalakeAdmin(String user) {+ User addMetalakeAdmin(String user) {UserEntity userEntity =UserEntity.builder()@@ -63,7 +55,7 @@ class AdminManager {Entity.SYSTEM_METALAKE_RESERVED_NAME,Entity.AUTHORIZATION_CATALOG_NAME,Entity.ADMIN_SCHEMA_NAME))- .withRoles(Lists.newArrayList())+ .withRoleNames(Lists.newArrayList()).withAuditInfo(AuditInfo.builder().withCreator(PrincipalUtils.getCurrentPrincipal().getName())@@ -82,14 +74,7 @@ class AdminManager {}}- /**- * Removes a metalake admin.- *- * @param user The name of the User.- * @return `true` if the User was successfully removed, `false` otherwise.- * @throws RuntimeException If removing the User encounters storage issues.- */- public boolean removeMetalakeAdmin(String user) {+ boolean removeMetalakeAdmin(String user) {try {return store.delete(ofMetalakeAdmin(user), Entity.EntityType.USER);} catch (IOException ioe) {@@ -99,23 +84,11 @@ class AdminManager {}}- /**- * Judges whether the user is the service admin.- *- * @param user the name of the user- * @return true, if the user is service admin, otherwise false.- */- public boolean isServiceAdmin(String user) {+ boolean isServiceAdmin(String user) {return serviceAdmins.contains(user);}- /**- * Judges whether the user is the metalake admin.- *- * @param user the name of the user- * @return true, if the user is metalake admin, otherwise false.- */- public boolean isMetalakeAdmin(String user) {+ boolean isMetalakeAdmin(String user) {try {return store.exists(ofMetalakeAdmin(user), Entity.EntityType.USER);} catch (IOException ioe) {diff --git a/core/src/main/java/com/datastrato/gravitino/authorization/AuthorizationUtils.java b/core/src/main/java/com/datastrato/gravitino/authorization/AuthorizationUtils.javaindex e5fa100b25..d6ded111e3 100644--- a/core/src/main/java/com/datastrato/gravitino/authorization/AuthorizationUtils.java+++ b/core/src/main/java/com/datastrato/gravitino/authorization/AuthorizationUtils.java@@ -6,8 +6,12 @@ package com.datastrato.gravitino.authorization;import com.datastrato.gravitino.Entity;import com.datastrato.gravitino.EntityStore;+import com.datastrato.gravitino.GravitinoEnv;import com.datastrato.gravitino.NameIdentifier;+import com.datastrato.gravitino.Namespace;import com.datastrato.gravitino.exceptions.NoSuchMetalakeException;+import com.datastrato.gravitino.meta.CatalogEntity;+import com.datastrato.gravitino.meta.SchemaEntity;import java.io.IOException;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -15,14 +19,18 @@ import org.slf4j.LoggerFactory;/* The utilization class of authorization module*/class AuthorizationUtils {+ static final String USER_DOES_NOT_EXIST_MSG = "User %s does not exist in th metalake %s";+ static final String GROUP_DOES_NOT_EXIST_MSG = "Group %s does not exist in th metalake %s";+ static final String ROLE_DOES_NOT_EXIST_MSG = "Role %s does not exist in th metalake %s";private static final Logger LOG = LoggerFactory.getLogger(AuthorizationUtils.class);private static final String METALAKE_DOES_NOT_EXIST_MSG = "Metalake %s does not exist";private AuthorizationUtils() {}- static void checkMetalakeExists(EntityStore store, String metalake)- throws NoSuchMetalakeException {+ static void checkMetalakeExists(String metalake) throws NoSuchMetalakeException {try {+ EntityStore store = GravitinoEnv.getInstance().entityStore();+NameIdentifier metalakeIdent = NameIdentifier.ofMetalake(metalake);if (!store.exists(metalakeIdent, Entity.EntityType.METALAKE)) {LOG.warn("Metalake {} does not exist", metalakeIdent);@@ -33,4 +41,32 @@ class AuthorizationUtils {throw new RuntimeException(e);}}++ public static NameIdentifier ofRole(String metalake, String role) {+ return NameIdentifier.of(+ metalake, Entity.SYSTEM_CATALOG_RESERVED_NAME, Entity.ROLE_SCHEMA_NAME, role);+ }++ public static NameIdentifier ofGroup(String metalake, String group) {+ return NameIdentifier.of(+ metalake, Entity.SYSTEM_CATALOG_RESERVED_NAME, Entity.GROUP_SCHEMA_NAME, group);+ }++ public static NameIdentifier ofUser(String metalake, String user) {+ return NameIdentifier.of(+ metalake, Entity.SYSTEM_CATALOG_RESERVED_NAME, Entity.USER_SCHEMA_NAME, user);+ }++ public static Namespace ofRoleNamespace(String metalake) {+ return Namespace.of(metalake, Entity.SYSTEM_CATALOG_RESERVED_NAME, Entity.ROLE_SCHEMA_NAME);+ }++ public static Namespace ofGroupNamespace(String metalake) {+ return Namespace.of(+ metalake, CatalogEntity.SYSTEM_CATALOG_RESERVED_NAME, SchemaEntity.GROUP_SCHEMA_NAME);+ }++ public static Namespace ofUserNamespace(String metalake) {+ return Namespace.of(metalake, Entity.SYSTEM_CATALOG_RESERVED_NAME, Entity.USER_SCHEMA_NAME);+ }}diff --git a/core/src/main/java/com/datastrato/gravitino/authorization/PermissionManager.java b/core/src/main/java/com/datastrato/gravitino/authorization/PermissionManager.javanew file mode 100644index 0000000000..4453e68d25--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/authorization/PermissionManager.java@@ -0,0 +1,277 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.gravitino.authorization;++import static com.datastrato.gravitino.authorization.AuthorizationUtils.GROUP_DOES_NOT_EXIST_MSG;+import static com.datastrato.gravitino.authorization.AuthorizationUtils.USER_DOES_NOT_EXIST_MSG;++import com.datastrato.gravitino.Entity;+import com.datastrato.gravitino.EntityStore;+import com.datastrato.gravitino.exceptions.NoSuchEntityException;+import com.datastrato.gravitino.exceptions.NoSuchGroupException;+import com.datastrato.gravitino.exceptions.NoSuchUserException;+import com.datastrato.gravitino.exceptions.RoleAlreadyExistsException;+import com.datastrato.gravitino.meta.AuditInfo;+import com.datastrato.gravitino.meta.GroupEntity;+import com.datastrato.gravitino.meta.RoleEntity;+import com.datastrato.gravitino.meta.UserEntity;+import com.datastrato.gravitino.utils.PrincipalUtils;+import com.google.common.collect.Lists;+import java.io.IOException;+import java.time.Instant;+import java.util.List;+import java.util.concurrent.atomic.AtomicBoolean;+import java.util.stream.Collectors;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++/**+ * PermissionManager is used for managing the logic the granting and revoking roles. Role is used+ * for manging permissions. GrantManager will filter the invalid roles, too.+ */+class PermissionManager {+ private static final Logger LOG = LoggerFactory.getLogger(PermissionManager.class);++ private final EntityStore store;+ private final RoleManager roleManager;++ PermissionManager(EntityStore store, RoleManager roleManager) {+ this.store = store;+ this.roleManager = roleManager;+ }++ boolean grantRoleToUser(String metalake, String role, String user) {+ try {+ RoleEntity roleEntity = roleManager.loadRole(metalake, role);++ store.update(+ AuthorizationUtils.ofUser(metalake, user),+ UserEntity.class,+ Entity.EntityType.USER,+ userEntity -> {+ List<RoleEntity> roleEntities =+ roleManager.getValidRoles(metalake, userEntity.roleNames(), userEntity.roleIds());++ List<String> roleNames = Lists.newArrayList(toRoleNames(roleEntities));+ List<Long> roleIds = Lists.newArrayList(toRoleIds(roleEntities));++ if (roleNames.contains(roleEntity.name())) {+ throw new RoleAlreadyExistsException(+ "Role %s already exists in the user %s of the metalake %s", role, user, metalake);+ }++ roleNames.add(roleEntity.name());+ roleIds.add(roleEntity.id());+ AuditInfo auditInfo =+ AuditInfo.builder()+ .withCreator(userEntity.auditInfo().creator())+ .withCreateTime(userEntity.auditInfo().createTime())+ .withLastModifier(PrincipalUtils.getCurrentPrincipal().getName())+ .withLastModifiedTime(Instant.now())+ .build();++ return UserEntity.builder()+ .withNamespace(userEntity.namespace())+ .withId(userEntity.id())+ .withName(userEntity.name())+ .withRoleNames(roleNames)+ .withRoleIds(roleIds)+ .withAuditInfo(auditInfo)+ .build();+ });+ return true;+ } catch (NoSuchEntityException nse) {+ LOG.warn("Failed to grant, user {} does not exist in the metalake {}", user, metalake, nse);+ throw new NoSuchUserException(USER_DOES_NOT_EXIST_MSG, user, metalake);+ } catch (IOException ioe) {+ LOG.error(+ "Failed to grant role {} to user {} in the metalake {} due to storage issues",+ role,+ user,+ metalake,+ ioe);+ throw new RuntimeException(ioe);+ }+ }++ boolean grantRoleToGroup(String metalake, String role, String group) {+ try {+ RoleEntity roleEntity = roleManager.loadRole(metalake, role);++ store.update(+ AuthorizationUtils.ofGroup(metalake, group),+ GroupEntity.class,+ Entity.EntityType.GROUP,+ groupEntity -> {+ List<RoleEntity> roleEntities =+ roleManager.getValidRoles(metalake, groupEntity.roleNames(), groupEntity.roleIds());+ List<String> roleNames = Lists.newArrayList(toRoleNames(roleEntities));+ List<Long> roleIds = Lists.newArrayList(toRoleIds(roleEntities));++ if (roleNames.contains(roleEntity.name())) {+ throw new RoleAlreadyExistsException(+ "Role %s already exists in the group %s of the metalake %s",+ role, group, metalake);+ }++ AuditInfo auditInfo =+ AuditInfo.builder()+ .withCreator(groupEntity.auditInfo().creator())+ .withCreateTime(groupEntity.auditInfo().createTime())+ .withLastModifier(PrincipalUtils.getCurrentPrincipal().getName())+ .withLastModifiedTime(Instant.now())+ .build();++ roleNames.add(roleEntity.name());+ roleIds.add(roleEntity.id());+ return GroupEntity.builder()+ .withId(groupEntity.id())+ .withNamespace(groupEntity.namespace())+ .withName(groupEntity.name())+ .withRoleNames(roleNames)+ .withRoleIds(roleIds)+ .withAuditInfo(auditInfo)+ .build();+ });+ return true;+ } catch (NoSuchEntityException nse) {+ LOG.warn("Failed to grant, group {} does not exist in the metalake {}", group, metalake, nse);+ throw new NoSuchGroupException(GROUP_DOES_NOT_EXIST_MSG, group, metalake);+ } catch (IOException ioe) {+ LOG.error(+ "Failed to grant role {} to group {} in the metalake {} due to storage issues",+ role,+ group,+ metalake,+ ioe);+ throw new RuntimeException(ioe);+ }+ }++ boolean revokeRoleFromGroup(String metalake, String role, String group) {+ try {+ RoleEntity roleEntity = roleManager.loadRole(metalake, role);++ AtomicBoolean removed = new AtomicBoolean(true);++ store.update(+ AuthorizationUtils.ofGroup(metalake, group),+ GroupEntity.class,+ Entity.EntityType.GROUP,+ groupEntity -> {+ List<RoleEntity> roleEntities =+ roleManager.getValidRoles(metalake, groupEntity.roleNames(), groupEntity.roleIds());+ List<String> roleNames = Lists.newArrayList(toRoleNames(roleEntities));+ List<Long> roleIds = Lists.newArrayList(toRoleIds(roleEntities));+ roleNames.remove(roleEntity.name());+ removed.set(roleIds.remove(roleEntity.id()));++ if (!removed.get()) {+ LOG.warn(+ "Failed to revoke, role {} does not exist in the group {} of metalake {}",+ role,+ group,+ metalake);+ }++ AuditInfo auditInfo =+ AuditInfo.builder()+ .withCreator(groupEntity.auditInfo().creator())+ .withCreateTime(groupEntity.auditInfo().createTime())+ .withLastModifier(PrincipalUtils.getCurrentPrincipal().getName())+ .withLastModifiedTime(Instant.now())+ .build();++ return GroupEntity.builder()+ .withNamespace(groupEntity.namespace())+ .withId(groupEntity.id())+ .withName(groupEntity.name())+ .withRoleNames(roleNames)+ .withRoleIds(roleIds)+ .withAuditInfo(auditInfo)+ .build();+ });++ return removed.get();+ } catch (NoSuchEntityException nse) {+ LOG.warn(+ "Failed to revoke, group {} does not exist in the metalake {}", group, metalake, nse);+ throw new NoSuchGroupException(GROUP_DOES_NOT_EXIST_MSG, group, metalake);+ } catch (IOException ioe) {+ LOG.error(+ "Failed to revoke role {} from group {} in the metalake {} due to storage issues",+ role,+ group,+ metalake,+ ioe);+ throw new RuntimeException(ioe);+ }+ }++ boolean revokeRoleFromUser(String metalake, String role, String user) {+ try {+ RoleEntity roleEntity = roleManager.loadRole(metalake, role);+ AtomicBoolean removed = new AtomicBoolean(true);++ store.update(+ AuthorizationUtils.ofUser(metalake, user),+ UserEntity.class,+ Entity.EntityType.USER,+ userEntity -> {+ List<RoleEntity> roleEntities =+ roleManager.getValidRoles(metalake, userEntity.roleNames(), userEntity.roleIds());++ List<String> roleNames = Lists.newArrayList(toRoleNames(roleEntities));+ List<Long> roleIds = Lists.newArrayList(toRoleIds(roleEntities));++ roleNames.remove(roleEntity.name());+ removed.set(roleIds.remove(roleEntity.id()));+ if (!removed.get()) {+ LOG.warn(+ "Failed to revoke, role {} doesn't exist in the user {} of metalake {}",+ role,+ user,+ metalake);+ }++ AuditInfo auditInfo =+ AuditInfo.builder()+ .withCreator(userEntity.auditInfo().creator())+ .withCreateTime(userEntity.auditInfo().createTime())+ .withLastModifier(PrincipalUtils.getCurrentPrincipal().getName())+ .withLastModifiedTime(Instant.now())+ .build();+ return UserEntity.builder()+ .withId(userEntity.id())+ .withNamespace(userEntity.namespace())+ .withName(userEntity.name())+ .withRoleNames(roleNames)+ .withRoleIds(roleIds)+ .withAuditInfo(auditInfo)+ .build();+ });+ return removed.get();+ } catch (NoSuchEntityException nse) {+ LOG.warn("Failed to revoke, user {} does not exist in the metalake {}", user, metalake, nse);+ throw new NoSuchUserException(USER_DOES_NOT_EXIST_MSG, user, metalake);+ } catch (IOException ioe) {+ LOG.error(+ "Failed to revoke role {} from user {} in the metalake {} due to storage issues",+ role,+ user,+ metalake,+ ioe);+ throw new RuntimeException(ioe);+ }+ }++ private List<String> toRoleNames(List<RoleEntity> roleEntities) {+ return roleEntities.stream().map(RoleEntity::name).collect(Collectors.toList());+ }++ private List<Long> toRoleIds(List<RoleEntity> roleEntities) {+ return roleEntities.stream().map(RoleEntity::id).collect(Collectors.toList());+ }+}diff --git a/core/src/main/java/com/datastrato/gravitino/authorization/RoleManager.java b/core/src/main/java/com/datastrato/gravitino/authorization/RoleManager.javaindex 35639e4726..ce39659996 100644--- a/core/src/main/java/com/datastrato/gravitino/authorization/RoleManager.java+++ b/core/src/main/java/com/datastrato/gravitino/authorization/RoleManager.java@@ -5,11 +5,12 @@package com.datastrato.gravitino.authorization;+import com.datastrato.gravitino.Config;+import com.datastrato.gravitino.Configs;import com.datastrato.gravitino.Entity;import com.datastrato.gravitino.EntityAlreadyExistsException;import com.datastrato.gravitino.EntityStore;import com.datastrato.gravitino.NameIdentifier;-import com.datastrato.gravitino.Namespace;import com.datastrato.gravitino.exceptions.NoSuchEntityException;import com.datastrato.gravitino.exceptions.NoSuchRoleException;import com.datastrato.gravitino.exceptions.RoleAlreadyExistsException;@@ -17,10 +18,18 @@ import com.datastrato.gravitino.meta.AuditInfo;import com.datastrato.gravitino.meta.RoleEntity;import com.datastrato.gravitino.storage.IdGenerator;import com.datastrato.gravitino.utils.PrincipalUtils;+import com.github.benmanes.caffeine.cache.Cache;+import com.github.benmanes.caffeine.cache.Caffeine;+import com.github.benmanes.caffeine.cache.Scheduler;+import com.google.common.annotations.VisibleForTesting;+import com.google.common.collect.Lists;+import com.google.common.util.concurrent.ThreadFactoryBuilder;import java.io.IOException;import java.time.Instant;import java.util.List;import java.util.Map;+import java.util.concurrent.ScheduledThreadPoolExecutor;+import java.util.concurrent.TimeUnit;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -32,35 +41,44 @@ import org.slf4j.LoggerFactory;class RoleManager {private static final Logger LOG = LoggerFactory.getLogger(RoleManager.class);- private static final String ROLE_DOES_NOT_EXIST_MSG = "Role %s does not exist in th metalake %s";private final EntityStore store;private final IdGenerator idGenerator;+ private final Cache<NameIdentifier, RoleEntity> cache;- public RoleManager(EntityStore store, IdGenerator idGenerator) {+ RoleManager(EntityStore store, IdGenerator idGenerator, Config config) {this.store = store;this.idGenerator = idGenerator;++ long cacheEvictionIntervalInMs = config.get(Configs.ROLE_CACHE_EVICTION_INTERVAL_MS);+ // One role entity is about 40 bytes using jol estimate, there are usually about 100w++ // roles in the production environment, this won't bring too much memory cost, but it+ // can improve the performance significantly.+ this.cache =+ Caffeine.newBuilder()+ .expireAfterAccess(cacheEvictionIntervalInMs, TimeUnit.MILLISECONDS)+ .removalListener(+ (k, v, c) -> {+ LOG.info("Remove role {} from the cache.", k);+ })+ .scheduler(+ Scheduler.forScheduledExecutorService(+ new ScheduledThreadPoolExecutor(+ 1,+ new ThreadFactoryBuilder()+ .setDaemon(true)+ .setNameFormat("role-cleaner-%d")+ .build())))+ .build();}- /**- * Creates a new Role.- *- * @param metalake The Metalake of the Role.- * @param role The name of the Role.- * @param properties The properties of the Role.- * @param securableObject The securable object of the Role.- * @param privileges The privileges of the Role.- * @return The created Role instance.- * @throws RoleAlreadyExistsException If a Role with the same identifier already exists.- * @throws RuntimeException If creating the Role encounters storage issues.- */- public Role createRole(+ RoleEntity createRole(String metalake,String role,Map<String, String> properties,SecurableObject securableObject,List<Privilege> privileges)throws RoleAlreadyExistsException {- AuthorizationUtils.checkMetalakeExists(store, metalake);+ AuthorizationUtils.checkMetalakeExists(metalake);RoleEntity roleEntity =RoleEntity.builder().withId(idGenerator.nextId())@@ -68,9 +86,7 @@ class RoleManager {.withProperties(properties).withSecurableObject(securableObject).withPrivileges(privileges)- .withNamespace(- Namespace.of(- metalake, Entity.SYSTEM_CATALOG_RESERVED_NAME, Entity.ROLE_SCHEMA_NAME))+ .withNamespace(AuthorizationUtils.ofRoleNamespace(metalake)).withAuditInfo(AuditInfo.builder().withCreator(PrincipalUtils.getCurrentPrincipal().getName())@@ -79,6 +95,7 @@ class RoleManager {.build();try {store.put(roleEntity, false /* overwritten */);+ cache.put(roleEntity.nameIdentifier(), roleEntity);return roleEntity;} catch (EntityAlreadyExistsException e) {LOG.warn("Role {} in the metalake {} already exists", role, metalake, e);@@ -91,40 +108,23 @@ class RoleManager {}}- /**- * Loads a Role.- *- * @param metalake The Metalake of the Role.- * @param role The name of the Role.- * @return The loading Role instance.- * @throws NoSuchRoleException If the Role with the given identifier does not exist.- * @throws RuntimeException If loading the Role encounters storage issues.- */- public Role loadRole(String metalake, String role) throws NoSuchRoleException {+ RoleEntity loadRole(String metalake, String role) throws NoSuchRoleException {try {- AuthorizationUtils.checkMetalakeExists(store, metalake);- return store.get(ofRole(metalake, role), Entity.EntityType.ROLE, RoleEntity.class);+ AuthorizationUtils.checkMetalakeExists(metalake);+ return getRoleEntity(AuthorizationUtils.ofRole(metalake, role));} catch (NoSuchEntityException e) {LOG.warn("Role {} does not exist in the metalake {}", role, metalake, e);- throw new NoSuchRoleException(ROLE_DOES_NOT_EXIST_MSG, role, metalake);- } catch (IOException ioe) {- LOG.error("Loading role {} failed due to storage issues", role, ioe);- throw new RuntimeException(ioe);+ throw new NoSuchRoleException(AuthorizationUtils.ROLE_DOES_NOT_EXIST_MSG, role, metalake);}}- /**- * Drops a Role.- *- * @param metalake The Metalake of the Role.- * @param role The name of the Role.- * @return `true` if the Role was successfully dropped, `false` otherwise.- * @throws RuntimeException If dropping the User encounters storage issues.- */- public boolean dropRole(String metalake, String role) {+ boolean dropRole(String metalake, String role) {try {- AuthorizationUtils.checkMetalakeExists(store, metalake);- return store.delete(ofRole(metalake, role), Entity.EntityType.ROLE);+ AuthorizationUtils.checkMetalakeExists(metalake);+ NameIdentifier ident = AuthorizationUtils.ofRole(metalake, role);+ cache.invalidate(ident);++ return store.delete(ident, Entity.EntityType.ROLE);} catch (IOException ioe) {LOG.error("Deleting role {} in the metalake {} failed due to storage issues", role, metalake, ioe);@@ -132,8 +132,45 @@ class RoleManager {}}- private NameIdentifier ofRole(String metalake, String role) {- return NameIdentifier.of(- metalake, Entity.SYSTEM_CATALOG_RESERVED_NAME, Entity.ROLE_SCHEMA_NAME, role);+ private RoleEntity getRoleEntity(NameIdentifier identifier) {+ return cache.get(+ identifier,+ id -> {+ try {+ return store.get(identifier, Entity.EntityType.ROLE, RoleEntity.class);+ } catch (IOException ioe) {+ LOG.error("Failed to get roles {} due to storage issues", identifier, ioe);+ throw new RuntimeException(ioe);+ }+ });+ }++ @VisibleForTesting+ Cache<NameIdentifier, RoleEntity> getCache() {+ return cache;+ }++ List<RoleEntity> getValidRoles(String metalake, List<String> roleNames, List<Long> roleIds) {+ List<RoleEntity> roleEntities = Lists.newArrayList();+ if (roleNames == null || roleNames.isEmpty()) {+ return roleEntities;+ }++ int index = 0;+ for (String role : roleNames) {+ try {++ RoleEntity roleEntity = getRoleEntity(AuthorizationUtils.ofRole(metalake, role));++ if (roleEntity.id().equals(roleIds.get(index))) {+ roleEntities.add(roleEntity);+ }+ index++;++ } catch (NoSuchEntityException nse) {+ // ignore this entity+ }+ }+ return roleEntities;}}diff --git a/core/src/main/java/com/datastrato/gravitino/authorization/UserGroupManager.java b/core/src/main/java/com/datastrato/gravitino/authorization/UserGroupManager.javaindex 411c640a84..0baa6fe460 100644--- a/core/src/main/java/com/datastrato/gravitino/authorization/UserGroupManager.java+++ b/core/src/main/java/com/datastrato/gravitino/authorization/UserGroupManager.java@@ -7,8 +7,6 @@ package com.datastrato.gravitino.authorization;import com.datastrato.gravitino.Entity;import com.datastrato.gravitino.EntityAlreadyExistsException;import com.datastrato.gravitino.EntityStore;-import com.datastrato.gravitino.NameIdentifier;-import com.datastrato.gravitino.Namespace;import com.datastrato.gravitino.exceptions.GroupAlreadyExistsException;import com.datastrato.gravitino.exceptions.NoSuchEntityException;import com.datastrato.gravitino.exceptions.NoSuchGroupException;@@ -16,6 +14,7 @@ import com.datastrato.gravitino.exceptions.NoSuchUserException;import com.datastrato.gravitino.exceptions.UserAlreadyExistsException;import com.datastrato.gravitino.meta.AuditInfo;import com.datastrato.gravitino.meta.GroupEntity;+import com.datastrato.gravitino.meta.RoleEntity;import com.datastrato.gravitino.meta.UserEntity;import com.datastrato.gravitino.storage.IdGenerator;import com.datastrato.gravitino.utils.PrincipalUtils;@@ -23,6 +22,8 @@ import com.google.common.collect.Lists;import java.io.IOException;import java.time.Instant;import java.util.Collections;+import java.util.List;+import java.util.stream.Collectors;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -35,39 +36,26 @@ import org.slf4j.LoggerFactory;class UserGroupManager {private static final Logger LOG = LoggerFactory.getLogger(UserGroupManager.class);- private static final String USER_DOES_NOT_EXIST_MSG = "User %s does not exist in th metalake %s";-- private static final String GROUP_DOES_NOT_EXIST_MSG =- "Group %s does not exist in th metalake %s";private final EntityStore store;private final IdGenerator idGenerator;+ private final RoleManager roleManager;- public UserGroupManager(EntityStore store, IdGenerator idGenerator) {+ UserGroupManager(EntityStore store, IdGenerator idGenerator, RoleManager roleManager) {this.store = store;this.idGenerator = idGenerator;+ this.roleManager = roleManager;}- /**- * Adds a new User.- *- * @param metalake The Metalake of the User.- * @param name The name of the User.- * @return The added User instance.- * @throws UserAlreadyExistsException If a User with the same identifier already exists.- * @throws RuntimeException If adding the User encounters storage issues.- */- public User addUser(String metalake, String name) throws UserAlreadyExistsException {+ User addUser(String metalake, String name) throws UserAlreadyExistsException {try {- AuthorizationUtils.checkMetalakeExists(store, metalake);+ AuthorizationUtils.checkMetalakeExists(metalake);UserEntity userEntity =UserEntity.builder().withId(idGenerator.nextId()).withName(name)- .withNamespace(- Namespace.of(- metalake, Entity.SYSTEM_CATALOG_RESERVED_NAME, Entity.USER_SCHEMA_NAME))- .withRoles(Lists.newArrayList())+ .withNamespace(AuthorizationUtils.ofUserNamespace(metalake))+ .withRoleNames(Lists.newArrayList()).withAuditInfo(AuditInfo.builder().withCreator(PrincipalUtils.getCurrentPrincipal().getName())@@ -87,19 +75,10 @@ class UserGroupManager {}}- /**- * Removes a User.- *- * @param metalake The Metalake of the User.- * @param user THe name of the User.- * @return `true` if the User was successfully removed, `false` otherwise.- * @throws RuntimeException If removing the User encounters storage issues.- */- public boolean removeUser(String metalake, String user) {-+ boolean removeUser(String metalake, String user) {try {- AuthorizationUtils.checkMetalakeExists(store, metalake);- return store.delete(ofUser(metalake, user), Entity.EntityType.USER);+ AuthorizationUtils.checkMetalakeExists(metalake);+ return store.delete(AuthorizationUtils.ofUser(metalake, user), Entity.EntityType.USER);} catch (IOException ioe) {LOG.error("Removing user {} in the metalake {} failed due to storage issues", user, metalake, ioe);@@ -107,48 +86,41 @@ class UserGroupManager {}}- /**- * Gets a User.- *- * @param metalake The Metalake of the User.- * @param user The name of the User.- * @return The getting User instance.- * @throws NoSuchUserException If the User with the given identifier does not exist.- * @throws RuntimeException If getting the User encounters storage issues.- */- public User getUser(String metalake, String user) throws NoSuchUserException {+ User getUser(String metalake, String user) throws NoSuchUserException {try {- AuthorizationUtils.checkMetalakeExists(store, metalake);- return store.get(ofUser(metalake, user), Entity.EntityType.USER, UserEntity.class);+ AuthorizationUtils.checkMetalakeExists(metalake);+ UserEntity entity =+ store.get(+ AuthorizationUtils.ofUser(metalake, user), Entity.EntityType.USER, UserEntity.class);++ List<RoleEntity> roleEntities =+ roleManager.getValidRoles(metalake, entity.roles(), entity.roleIds());++ return UserEntity.builder()+ .withId(entity.id())+ .withName(entity.name())+ .withAuditInfo(entity.auditInfo())+ .withNamespace(entity.namespace())+ .withRoleNames(roleEntities.stream().map(RoleEntity::name).collect(Collectors.toList()))+ .build();} catch (NoSuchEntityException e) {LOG.warn("User {} does not exist in the metalake {}", user, metalake, e);- throw new NoSuchUserException(USER_DOES_NOT_EXIST_MSG, user, metalake);+ throw new NoSuchUserException(AuthorizationUtils.USER_DOES_NOT_EXIST_MSG, user, metalake);} catch (IOException ioe) {LOG.error("Getting user {} failed due to storage issues", user, ioe);throw new RuntimeException(ioe);}}- /**- * Adds a new Group.- *- * @param metalake The Metalake of the Group.- * @param group The name of the Group.- * @return The Added Group instance.- * @throws GroupAlreadyExistsException If a Group with the same identifier already exists.- * @throws RuntimeException If adding the Group encounters storage issues.- */- public Group addGroup(String metalake, String group) throws GroupAlreadyExistsException {+ Group addGroup(String metalake, String group) throws GroupAlreadyExistsException {try {- AuthorizationUtils.checkMetalakeExists(store, metalake);+ AuthorizationUtils.checkMetalakeExists(metalake);GroupEntity groupEntity =GroupEntity.builder().withId(idGenerator.nextId()).withName(group)- .withNamespace(- Namespace.of(- metalake, Entity.SYSTEM_CATALOG_RESERVED_NAME, Entity.GROUP_SCHEMA_NAME))- .withRoles(Collections.emptyList())+ .withNamespace(AuthorizationUtils.ofGroupNamespace(metalake))+ .withRoleNames(Collections.emptyList()).withAuditInfo(AuditInfo.builder().withCreator(PrincipalUtils.getCurrentPrincipal().getName())@@ -168,18 +140,10 @@ class UserGroupManager {}}- /**- * Removes a Group.- *- * @param metalake The Metalake of the Group.- * @param group THe name of the Group.- * @return `true` if the Group was successfully removed, `false` otherwise.- * @throws RuntimeException If removing the Group encounters storage issues.- */- public boolean removeGroup(String metalake, String group) {+ boolean removeGroup(String metalake, String group) {try {- AuthorizationUtils.checkMetalakeExists(store, metalake);- return store.delete(ofGroup(metalake, group), Entity.EntityType.GROUP);+ AuthorizationUtils.checkMetalakeExists(metalake);+ return store.delete(AuthorizationUtils.ofGroup(metalake, group), Entity.EntityType.GROUP);} catch (IOException ioe) {LOG.error("Removing group {} in the metalake {} failed due to storage issues",@@ -190,35 +154,32 @@ class UserGroupManager {}}- /**- * Gets a Group.- *- * @param metalake The Metalake of the Group.- * @param group THe name of the Group.- * @return The getting Group instance.- * @throws NoSuchGroupException If the Group with the given identifier does not exist.- * @throws RuntimeException If getting the Group encounters storage issues.- */- public Group getGroup(String metalake, String group) {+ Group getGroup(String metalake, String group) {try {- AuthorizationUtils.checkMetalakeExists(store, metalake);- return store.get(ofGroup(metalake, group), Entity.EntityType.GROUP, GroupEntity.class);+ AuthorizationUtils.checkMetalakeExists(metalake);++ GroupEntity entity =+ store.get(+ AuthorizationUtils.ofGroup(metalake, group),+ Entity.EntityType.GROUP,+ GroupEntity.class);++ List<RoleEntity> roleEntities =+ roleManager.getValidRoles(metalake, entity.roles(), entity.roleIds());++ return GroupEntity.builder()+ .withId(entity.id())+ .withName(entity.name())+ .withAuditInfo(entity.auditInfo())+ .withNamespace(entity.namespace())+ .withRoleNames(roleEntities.stream().map(RoleEntity::name).collect(Collectors.toList()))+ .build();} catch (NoSuchEntityException e) {LOG.warn("Group {} does not exist in the metalake {}", group, metalake, e);- throw new NoSuchGroupException(GROUP_DOES_NOT_EXIST_MSG, group, metalake);+ throw new NoSuchGroupException(AuthorizationUtils.GROUP_DOES_NOT_EXIST_MSG, group, metalake);} catch (IOException ioe) {LOG.error("Getting group {} failed due to storage issues", group, ioe);throw new RuntimeException(ioe);}}-- private NameIdentifier ofUser(String metalake, String user) {- return NameIdentifier.of(- metalake, Entity.SYSTEM_CATALOG_RESERVED_NAME, Entity.USER_SCHEMA_NAME, user);- }-- private NameIdentifier ofGroup(String metalake, String group) {- return NameIdentifier.of(- metalake, Entity.SYSTEM_CATALOG_RESERVED_NAME, Entity.GROUP_SCHEMA_NAME, group);- }}diff --git a/core/src/main/java/com/datastrato/gravitino/meta/GroupEntity.java b/core/src/main/java/com/datastrato/gravitino/meta/GroupEntity.javaindex e00b59b908..f9c3b9cd88 100644--- a/core/src/main/java/com/datastrato/gravitino/meta/GroupEntity.java+++ b/core/src/main/java/com/datastrato/gravitino/meta/GroupEntity.java@@ -24,8 +24,11 @@ public class GroupEntity implements Group, Entity, Auditable, HasIdentifier {public static final Field NAME =Field.required("name", String.class, "The name of the group entity.");- public static final Field ROLES =- Field.optional("roles", List.class, "The roles of the group entity.");+ public static final Field ROLE_NAMES =+ Field.optional("role_names", List.class, "The role names of the group entity.");++ public static final Field ROLE_IDS =+ Field.optional("role_ids", List.class, "The role names of the group entity.");public static final Field AUDIT_INFO =Field.required("audit_info", AuditInfo.class, "The audit details of the group entity.");@@ -33,7 +36,8 @@ public class GroupEntity implements Group, Entity, Auditable, HasIdentifier {private Long id;private String name;private AuditInfo auditInfo;- private List<String> roles;+ private List<String> roleNames;+ private List<Long> roleIds;private Namespace namespace;private GroupEntity() {}@@ -49,7 +53,8 @@ public class GroupEntity implements Group, Entity, Auditable, HasIdentifier {fields.put(ID, id);fields.put(NAME, name);fields.put(AUDIT_INFO, auditInfo);- fields.put(ROLES, roles);+ fields.put(ROLE_NAMES, roleNames);+ fields.put(ROLE_IDS, roleIds);return Collections.unmodifiableMap(fields);}@@ -109,7 +114,25 @@ public class GroupEntity implements Group, Entity, Auditable, HasIdentifier {* @return The roles of the group entity.*/public List<String> roles() {- return roles;+ return roleNames;+ }++ /**+ * Returns the role names of the group entity.+ *+ * @return The role names of the group entity.+ */+ public List<String> roleNames() {+ return roleNames;+ }++ /**+ * Returns the role ids of the group entity.+ *+ * @return The role ids of the group entity.+ */+ public List<Long> roleIds() {+ return roleIds;}@Override@@ -122,12 +145,13 @@ public class GroupEntity implements Group, Entity, Auditable, HasIdentifier {&& Objects.equals(name, that.name)&& Objects.equals(namespace, that.namespace)&& Objects.equals(auditInfo, that.auditInfo)- && Objects.equals(roles, that.roles);+ && Objects.equals(roleNames, that.roleNames)+ && Objects.equals(roleIds, that.roleIds);}@Overridepublic int hashCode() {- return Objects.hash(id, name, auditInfo, roles);+ return Objects.hash(id, name, auditInfo, roleNames, roleIds);}public static Builder builder() {@@ -175,13 +199,24 @@ public class GroupEntity implements Group, Entity, Auditable, HasIdentifier {}/**- * Sets the roles of the group entity.+ * Sets the role names of the group entity.+ *+ * @param roles The role names of the group entity.+ * @return The builder instance.+ */+ public Builder withRoleNames(List<String> roles) {+ groupEntity.roleNames = roles;+ return this;+ }++ /**+ * Sets the role ids of the group entity.*- * @param roles The roles of the group entity.+ * @param roleIds The role ids of the group entity.* @return The builder instance.*/- public Builder withRoles(List<String> roles) {- groupEntity.roles = roles;+ public Builder withRoleIds(List<Long> roleIds) {+ groupEntity.roleIds = roleIds;return this;}diff --git a/core/src/main/java/com/datastrato/gravitino/meta/UserEntity.java b/core/src/main/java/com/datastrato/gravitino/meta/UserEntity.javaindex 933ecb1eb5..954ec9924e 100644--- a/core/src/main/java/com/datastrato/gravitino/meta/UserEntity.java+++ b/core/src/main/java/com/datastrato/gravitino/meta/UserEntity.java@@ -30,13 +30,17 @@ public class UserEntity implements User, Entity, Auditable, HasIdentifier {public static final Field AUDIT_INFO =Field.required("audit_info", AuditInfo.class, "The audit details of the user entity.");- public static final Field ROLES =- Field.optional("roles", List.class, "The roles of the user entity");+ public static final Field ROLE_NAMES =+ Field.optional("role_names", List.class, "The role names of the user entity");++ public static final Field ROLE_IDS =+ Field.optional("role_ids", List.class, "The role ids of the user entity");private Long id;private String name;private AuditInfo auditInfo;- private List<String> roles;+ private List<String> roleNames;+ private List<Long> roleIds;private Namespace namespace;private UserEntity() {}@@ -52,7 +56,8 @@ public class UserEntity implements User, Entity, Auditable, HasIdentifier {fields.put(ID, id);fields.put(NAME, name);fields.put(AUDIT_INFO, auditInfo);- fields.put(ROLES, roles);+ fields.put(ROLE_NAMES, roleNames);+ fields.put(ROLE_IDS, roleIds);return Collections.unmodifiableMap(fields);}@@ -113,7 +118,25 @@ public class UserEntity implements User, Entity, Auditable, HasIdentifier {*/@Overridepublic List<String> roles() {- return roles;+ return roleNames;+ }++ /**+ * Returns the role names of the user entity.+ *+ * @return The role names of the user entity.+ */+ public List<String> roleNames() {+ return roleNames;+ }++ /**+ * Returns the role ids of the user entity.+ *+ * @return The role ids of the user entity.+ */+ public List<Long> roleIds() {+ return roleIds;}@Override@@ -126,12 +149,13 @@ public class UserEntity implements User, Entity, Auditable, HasIdentifier {&& Objects.equals(name, that.name)&& Objects.equals(namespace, that.namespace)&& Objects.equals(auditInfo, that.auditInfo)- && Objects.equals(roles, that.roles);+ && Objects.equals(roleNames, that.roleNames)+ && Objects.equals(roleIds, that.roleIds);}@Overridepublic int hashCode() {- return Objects.hash(id, name, auditInfo, roles);+ return Objects.hash(id, name, auditInfo, roleNames, roleIds);}public static Builder builder() {@@ -179,13 +203,24 @@ public class UserEntity implements User, Entity, Auditable, HasIdentifier {}/**- * Sets the roles of the user entity.+ * Sets the role names of the user entity.+ *+ * @param roles The role names of the user entity.+ * @return The builder instance.+ */+ public Builder withRoleNames(List<String> roles) {+ userEntity.roleNames = roles;+ return this;+ }++ /**+ * Sets the role ids of the user entity.*- * @param roles The roles of the user entity.+ * @param roleIds The role ids of the user entity.* @return The builder instance.*/- public Builder withRoles(List<String> roles) {- userEntity.roles = roles;+ public Builder withRoleIds(List<Long> roleIds) {+ userEntity.roleIds = roleIds;return this;}diff --git a/core/src/main/java/com/datastrato/gravitino/proto/GroupEntitySerDe.java b/core/src/main/java/com/datastrato/gravitino/proto/GroupEntitySerDe.javaindex e1fa6ab50c..fb5465802d 100644--- a/core/src/main/java/com/datastrato/gravitino/proto/GroupEntitySerDe.java+++ b/core/src/main/java/com/datastrato/gravitino/proto/GroupEntitySerDe.java@@ -19,7 +19,11 @@ public class GroupEntitySerDe implements ProtoSerDe<GroupEntity, Group> {.setAuditInfo(new AuditInfoSerDe().serialize(groupEntity.auditInfo()));if (isCollectionNotEmpty(groupEntity.roles())) {- builder.addAllRoles(groupEntity.roles());+ builder.addAllRoleNames(groupEntity.roles());+ }++ if (isCollectionNotEmpty(groupEntity.roleIds())) {+ builder.addAllRoleIds(groupEntity.roleIds());}return builder.build();@@ -34,8 +38,12 @@ public class GroupEntitySerDe implements ProtoSerDe<GroupEntity, Group> {.withNamespace(namespace).withAuditInfo(new AuditInfoSerDe().deserialize(group.getAuditInfo(), namespace));- if (group.getRolesCount() > 0) {- builder.withRoles(group.getRolesList());+ if (group.getRoleNamesCount() > 0) {+ builder.withRoleNames(group.getRoleNamesList());+ }++ if (group.getRoleIdsCount() > 0) {+ builder.withRoleIds(group.getRoleIdsList());}return builder.build();diff --git a/core/src/main/java/com/datastrato/gravitino/proto/UserEntitySerDe.java b/core/src/main/java/com/datastrato/gravitino/proto/UserEntitySerDe.javaindex 47e7f2bb18..c839b574e3 100644--- a/core/src/main/java/com/datastrato/gravitino/proto/UserEntitySerDe.java+++ b/core/src/main/java/com/datastrato/gravitino/proto/UserEntitySerDe.java@@ -19,7 +19,11 @@ public class UserEntitySerDe implements ProtoSerDe<UserEntity, User> {.setAuditInfo(new AuditInfoSerDe().serialize(userEntity.auditInfo()));if (isCollectionNotEmpty(userEntity.roles())) {- builder.addAllRoles(userEntity.roles());+ builder.addAllRoleNames(userEntity.roles());+ }++ if (isCollectionNotEmpty(userEntity.roleIds())) {+ builder.addAllRoleIds(userEntity.roleIds());}return builder.build();@@ -34,8 +38,12 @@ public class UserEntitySerDe implements ProtoSerDe<UserEntity, User> {.withNamespace(namespace).withAuditInfo(new AuditInfoSerDe().deserialize(user.getAuditInfo(), namespace));- if (user.getRolesCount() > 0) {- builder.withRoles(user.getRolesList());+ if (user.getRoleNamesCount() > 0) {+ builder.withRoleNames(user.getRoleNamesList());+ }++ if (user.getRoleIdsCount() > 0) {+ builder.withRoleIds(user.getRoleIdsList());}return builder.build();diff --git a/core/src/test/java/com/datastrato/gravitino/authorization/TestAccessControlManager.java b/core/src/test/java/com/datastrato/gravitino/authorization/TestAccessControlManager.javaindex c53ada3a35..e65115c3c5 100644--- a/core/src/test/java/com/datastrato/gravitino/authorization/TestAccessControlManager.java+++ b/core/src/test/java/com/datastrato/gravitino/authorization/TestAccessControlManager.java@@ -8,6 +8,7 @@ import static com.datastrato.gravitino.Configs.SERVICE_ADMINS;import com.datastrato.gravitino.Config;import com.datastrato.gravitino.EntityStore;+import com.datastrato.gravitino.GravitinoEnv;import com.datastrato.gravitino.StringIdentifier;import com.datastrato.gravitino.exceptions.GroupAlreadyExistsException;import com.datastrato.gravitino.exceptions.NoSuchGroupException;@@ -39,12 +40,12 @@ public class TestAccessControlManager {private static Config config;- private static String metalake = "metalake";+ private static String METALAKE = "metalake";private static BaseMetalake metalakeEntity =BaseMetalake.builder().withId(1L)- .withName(metalake)+ .withName(METALAKE).withAuditInfo(AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build()).withVersion(SchemaVersion.V_0_1)@@ -62,6 +63,8 @@ public class TestAccessControlManager {entityStore.put(metalakeEntity, true);accessControlManager = new AccessControlManager(entityStore, new RandomIdGenerator(), config);+ GravitinoEnv.getInstance().setEntityStore(entityStore);+ GravitinoEnv.getInstance().setAccessControlManager(accessControlManager);}@AfterAll@@ -241,7 +244,14 @@ public class TestAccessControlManager {accessControlManager.createRole("metalake", "loadRole", props, SecurableObjects.ofAllCatalogs(), Lists.newArrayList());++ Role cachedRole = accessControlManager.loadRole("metalake", "loadRole");+ accessControlManager.getRoleManager().getCache().invalidateAll();Role role = accessControlManager.loadRole("metalake", "loadRole");++ // Verify the cached roleEntity is correct+ Assertions.assertEquals(role, cachedRole);+Assertions.assertEquals("loadRole", role.name());testProperties(props, role.properties());diff --git a/core/src/test/java/com/datastrato/gravitino/authorization/TestAccessControlManagerForPermissions.java b/core/src/test/java/com/datastrato/gravitino/authorization/TestAccessControlManagerForPermissions.javanew file mode 100644index 0000000000..00dd6127bc--- /dev/null+++ b/core/src/test/java/com/datastrato/gravitino/authorization/TestAccessControlManagerForPermissions.java@@ -0,0 +1,268 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.gravitino.authorization;++import com.datastrato.gravitino.Config;+import com.datastrato.gravitino.Entity;+import com.datastrato.gravitino.EntityStore;+import com.datastrato.gravitino.GravitinoEnv;+import com.datastrato.gravitino.Namespace;+import com.datastrato.gravitino.exceptions.NoSuchGroupException;+import com.datastrato.gravitino.exceptions.NoSuchMetalakeException;+import com.datastrato.gravitino.exceptions.NoSuchRoleException;+import com.datastrato.gravitino.exceptions.NoSuchUserException;+import com.datastrato.gravitino.exceptions.RoleAlreadyExistsException;+import com.datastrato.gravitino.meta.AuditInfo;+import com.datastrato.gravitino.meta.BaseMetalake;+import com.datastrato.gravitino.meta.GroupEntity;+import com.datastrato.gravitino.meta.RoleEntity;+import com.datastrato.gravitino.meta.SchemaVersion;+import com.datastrato.gravitino.meta.UserEntity;+import com.datastrato.gravitino.storage.RandomIdGenerator;+import com.datastrato.gravitino.storage.memory.TestMemoryEntityStore;+import com.google.common.collect.Lists;+import com.google.common.collect.Maps;+import java.io.IOException;+import java.time.Instant;+import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++public class TestAccessControlManagerForPermissions {++ private static AccessControlManager accessControlManager;++ private static EntityStore entityStore;++ private static Config config;++ private static String METALAKE = "metalake";+ private static String CATALOG = "catalog";++ private static String USER = "user";++ private static String GROUP = "group";++ private static String ROLE = "role";++ private static AuditInfo auditInfo =+ AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build();++ private static BaseMetalake metalakeEntity =+ BaseMetalake.builder()+ .withId(1L)+ .withName(METALAKE)+ .withAuditInfo(auditInfo)+ .withVersion(SchemaVersion.V_0_1)+ .build();++ private static UserEntity userEntity =+ UserEntity.builder()+ .withNamespace(+ Namespace.of(METALAKE, Entity.SYSTEM_CATALOG_RESERVED_NAME, Entity.USER_SCHEMA_NAME))+ .withId(1L)+ .withName(USER)+ .withAuditInfo(auditInfo)+ .build();++ private static GroupEntity groupEntity =+ GroupEntity.builder()+ .withNamespace(+ Namespace.of(METALAKE, Entity.SYSTEM_CATALOG_RESERVED_NAME, Entity.GROUP_SCHEMA_NAME))+ .withId(1L)+ .withName(GROUP)+ .withAuditInfo(auditInfo)+ .build();++ private static RoleEntity roleEntity =+ RoleEntity.builder()+ .withNamespace(+ Namespace.of(METALAKE, Entity.SYSTEM_CATALOG_RESERVED_NAME, Entity.ROLE_SCHEMA_NAME))+ .withId(1L)+ .withName(ROLE)+ .withProperties(Maps.newHashMap())+ .withPrivileges(Lists.newArrayList(Privileges.LoadCatalog.get()))+ .withSecurableObject(SecurableObjects.of(CATALOG))+ .withAuditInfo(auditInfo)+ .build();++ @BeforeAll+ public static void setUp() throws Exception {+ config = new Config(false) {};++ entityStore = new TestMemoryEntityStore.InMemoryEntityStore();+ entityStore.initialize(config);+ entityStore.setSerDe(null);++ entityStore.put(metalakeEntity, true);+ entityStore.put(userEntity, true);+ entityStore.put(groupEntity, true);+ entityStore.put(roleEntity, true);++ accessControlManager = new AccessControlManager(entityStore, new RandomIdGenerator(), config);++ GravitinoEnv.getInstance().setEntityStore(entityStore);+ GravitinoEnv.getInstance().setAccessControlManager(accessControlManager);+ }++ @AfterAll+ public static void tearDown() throws IOException {+ if (entityStore != null) {+ entityStore.close();+ entityStore = null;+ }+ }++ @Test+ public void testAddRoleToUser() {+ String notExist = "not-exist";++ User user = accessControlManager.getUser(METALAKE, USER);+ Assertions.assertTrue(user.roles().isEmpty());++ Assertions.assertTrue(accessControlManager.grantRoleToUser(METALAKE, ROLE, USER));+ user = accessControlManager.getUser(METALAKE, USER);+ Assertions.assertEquals(1, user.roles().size());+ Assertions.assertEquals(ROLE, user.roles().get(0));++ // Throw RoleAlreadyExistsException+ Assertions.assertThrows(+ RoleAlreadyExistsException.class,+ () -> accessControlManager.grantRoleToUser(METALAKE, ROLE, USER));++ // Throw NoSuchMetalakeException+ Assertions.assertThrows(+ NoSuchMetalakeException.class,+ () -> accessControlManager.grantRoleToUser(notExist, ROLE, USER));++ // Throw NoSuchRoleException+ Assertions.assertThrows(+ NoSuchRoleException.class,+ () -> accessControlManager.grantRoleToUser(METALAKE, notExist, USER));++ // Throw NoSuchUserException+ Assertions.assertThrows(+ NoSuchUserException.class,+ () -> accessControlManager.grantRoleToUser(METALAKE, ROLE, notExist));++ // Clear Resource+ Assertions.assertTrue(accessControlManager.revokeRoleFromUser(METALAKE, ROLE, USER));+ }++ @Test+ public void testRemoveRoleFromUser() {+ String notExist = "not-exist";++ Assertions.assertTrue(accessControlManager.grantRoleToUser(METALAKE, ROLE, USER));+ Assertions.assertTrue(accessControlManager.revokeRoleFromUser(METALAKE, ROLE, USER));++ // Throw NoSuchMetalakeException+ Assertions.assertThrows(+ NoSuchMetalakeException.class,+ () -> accessControlManager.revokeRoleFromUser(notExist, ROLE, USER));++ // Throw NoSuchRoleException+ Assertions.assertThrows(+ NoSuchRoleException.class,+ () -> accessControlManager.revokeRoleFromUser(METALAKE, notExist, USER));++ // Remove role which doesn't exist.+ Assertions.assertFalse(accessControlManager.revokeRoleFromUser(METALAKE, ROLE, USER));++ // Throw NoSuchUserException+ Assertions.assertThrows(+ NoSuchUserException.class,+ () -> accessControlManager.revokeRoleFromUser(METALAKE, ROLE, notExist));+ }++ @Test+ public void testAddRoleToGroup() {+ String notExist = "not-exist";++ Group group = accessControlManager.getGroup(METALAKE, GROUP);+ Assertions.assertTrue(group.roles().isEmpty());++ Assertions.assertTrue(accessControlManager.grantRoleToGroup(METALAKE, ROLE, GROUP));++ group = accessControlManager.getGroup(METALAKE, GROUP);+ Assertions.assertEquals(1, group.roles().size());+ Assertions.assertEquals(ROLE, group.roles().get(0));++ // Throw RoleAlreadyExistsException+ Assertions.assertThrows(+ RoleAlreadyExistsException.class,+ () -> accessControlManager.grantRoleToGroup(METALAKE, ROLE, GROUP));++ // Throw NoSuchMetalakeException+ Assertions.assertThrows(+ NoSuchMetalakeException.class,+ () -> accessControlManager.grantRoleToGroup(notExist, ROLE, GROUP));++ // Throw NoSuchRoleException+ Assertions.assertThrows(+ NoSuchRoleException.class,+ () -> accessControlManager.grantRoleToGroup(METALAKE, notExist, GROUP));++ // Throw NoSuchGroupException+ Assertions.assertThrows(+ NoSuchGroupException.class,+ () -> accessControlManager.grantRoleToGroup(METALAKE, ROLE, notExist));++ // Clear Resource+ Assertions.assertTrue(accessControlManager.revokeRoleFromGroup(METALAKE, ROLE, GROUP));+ }++ @Test+ public void testRemoveRoleFormGroup() {+ String notExist = "not-exist";++ Assertions.assertTrue(accessControlManager.grantRoleToGroup(METALAKE, ROLE, GROUP));+ Assertions.assertTrue(accessControlManager.revokeRoleFromGroup(METALAKE, ROLE, GROUP));++ // Throw NoSuchMetalakeException+ Assertions.assertThrows(+ NoSuchMetalakeException.class,+ () -> accessControlManager.revokeRoleFromGroup(notExist, ROLE, GROUP));++ // Throw NoSuchRoleException+ Assertions.assertThrows(+ NoSuchRoleException.class,+ () -> accessControlManager.revokeRoleFromGroup(METALAKE, notExist, USER));++ // Remove not exist role+ Assertions.assertFalse(accessControlManager.revokeRoleFromUser(METALAKE, ROLE, USER));++ // Throw NoSuchGroupException+ Assertions.assertThrows(+ NoSuchGroupException.class,+ () -> accessControlManager.revokeRoleFromGroup(METALAKE, ROLE, notExist));+ }++ @Test+ public void testDropRole() throws IOException {+ String anotherRole = "anotherRole";++ RoleEntity roleEntity =+ RoleEntity.builder()+ .withNamespace(+ Namespace.of(+ METALAKE, Entity.SYSTEM_CATALOG_RESERVED_NAME, Entity.ROLE_SCHEMA_NAME))+ .withId(1L)+ .withName(anotherRole)+ .withProperties(Maps.newHashMap())+ .withPrivileges(Lists.newArrayList(Privileges.LoadCatalog.get()))+ .withSecurableObject(SecurableObjects.ofCatalog(CATALOG))+ .withAuditInfo(auditInfo)+ .build();++ entityStore.put(roleEntity, true);+ Assertions.assertTrue(accessControlManager.grantRoleToUser(METALAKE, anotherRole, USER));+ Assertions.assertTrue(accessControlManager.grantRoleToGroup(METALAKE, anotherRole, GROUP));+ accessControlManager.dropRole(METALAKE, anotherRole);+ Group group = accessControlManager.getGroup(METALAKE, GROUP);+ Assertions.assertTrue(group.roles().isEmpty());+ }+}diff --git a/core/src/test/java/com/datastrato/gravitino/meta/TestEntity.java b/core/src/test/java/com/datastrato/gravitino/meta/TestEntity.javaindex b852d34010..7108f33ef8 100644--- a/core/src/test/java/com/datastrato/gravitino/meta/TestEntity.java+++ b/core/src/test/java/com/datastrato/gravitino/meta/TestEntity.java@@ -223,14 +223,14 @@ public class TestEntity {.withId(userId).withName(userName).withAuditInfo(auditInfo)- .withRoles(Lists.newArrayList("role"))+ .withRoleNames(Lists.newArrayList("role")).build();Map<Field, Object> fields = testUserEntity.fields();Assertions.assertEquals(userId, fields.get(UserEntity.ID));Assertions.assertEquals(userName, fields.get(UserEntity.NAME));Assertions.assertEquals(auditInfo, fields.get(UserEntity.AUDIT_INFO));- Assertions.assertEquals(Lists.newArrayList("role"), fields.get(UserEntity.ROLES));+ Assertions.assertEquals(Lists.newArrayList("role"), fields.get(UserEntity.ROLE_NAMES));UserEntity testUserEntityWithoutFields =UserEntity.builder().withId(userId).withName(userName).withAuditInfo(auditInfo).build();@@ -245,13 +245,13 @@ public class TestEntity {.withId(groupId).withName(groupName).withAuditInfo(auditInfo)- .withRoles(Lists.newArrayList("role"))+ .withRoleNames(Lists.newArrayList("role")).build();Map<Field, Object> fields = group.fields();Assertions.assertEquals(groupId, fields.get(GroupEntity.ID));Assertions.assertEquals(groupName, fields.get(GroupEntity.NAME));Assertions.assertEquals(auditInfo, fields.get(GroupEntity.AUDIT_INFO));- Assertions.assertEquals(Lists.newArrayList("role"), fields.get(GroupEntity.ROLES));+ Assertions.assertEquals(Lists.newArrayList("role"), fields.get(GroupEntity.ROLE_NAMES));GroupEntity groupWithoutFields =GroupEntity.builder().withId(userId).withName(userName).withAuditInfo(auditInfo).build();diff --git a/core/src/test/java/com/datastrato/gravitino/proto/TestEntityProtoSerDe.java b/core/src/test/java/com/datastrato/gravitino/proto/TestEntityProtoSerDe.javaindex d0b91b7915..a314a3f1c7 100644--- a/core/src/test/java/com/datastrato/gravitino/proto/TestEntityProtoSerDe.java+++ b/core/src/test/java/com/datastrato/gravitino/proto/TestEntityProtoSerDe.java@@ -321,7 +321,8 @@ public class TestEntityProtoSerDe {.withName(userName).withNamespace(userNamespace).withAuditInfo(auditInfo)- .withRoles(Lists.newArrayList("role"))+ .withRoleNames(Lists.newArrayList("role"))+ .withRoleIds(Lists.newArrayList(1L)).build();byte[] userBytes = protoEntitySerDe.serialize(userEntity);UserEntity userEntityFromBytes =@@ -339,6 +340,7 @@ public class TestEntityProtoSerDe {userEntityFromBytes = protoEntitySerDe.deserialize(userBytes, UserEntity.class, userNamespace);Assertions.assertEquals(userEntityWithoutFields, userEntityFromBytes);Assertions.assertNull(userEntityWithoutFields.roles());+ Assertions.assertNull(userEntityWithoutFields.roleIds());// Test GroupEntityNamespace groupNamespace =@@ -352,7 +354,8 @@ public class TestEntityProtoSerDe {.withName(groupName).withNamespace(groupNamespace).withAuditInfo(auditInfo)- .withRoles(Lists.newArrayList("role"))+ .withRoleNames(Lists.newArrayList("role"))+ .withRoleIds(Lists.newArrayList(1L)).build();byte[] groupBytes = protoEntitySerDe.serialize(group);GroupEntity groupFromBytes =@@ -370,6 +373,7 @@ public class TestEntityProtoSerDe {groupFromBytes = protoEntitySerDe.deserialize(groupBytes, GroupEntity.class, groupNamespace);Assertions.assertEquals(groupWithoutFields, groupFromBytes);Assertions.assertNull(groupWithoutFields.roles());+ Assertions.assertNull(groupWithoutFields.roleIds());// Test RoleEntityNamespace roleNamespace =diff --git a/core/src/test/java/com/datastrato/gravitino/storage/TestEntityStorage.java b/core/src/test/java/com/datastrato/gravitino/storage/TestEntityStorage.javaindex e79ccf9cac..3bd7cf8a70 100644--- a/core/src/test/java/com/datastrato/gravitino/storage/TestEntityStorage.java+++ b/core/src/test/java/com/datastrato/gravitino/storage/TestEntityStorage.java@@ -1160,7 +1160,7 @@ public class TestEntityStorage {Namespace.of(metalake, Entity.SYSTEM_CATALOG_RESERVED_NAME, Entity.USER_SCHEMA_NAME)).withName(name).withAuditInfo(auditInfo)- .withRoles(Lists.newArrayList())+ .withRoleNames(Lists.newArrayList()).build();}@@ -1171,7 +1171,7 @@ public class TestEntityStorage {Namespace.of(metalake, Entity.SYSTEM_CATALOG_RESERVED_NAME, Entity.GROUP_SCHEMA_NAME)).withName(name).withAuditInfo(auditInfo)- .withRoles(Lists.newArrayList())+ .withRoleNames(Lists.newArrayList()).build();}diff --git a/meta/src/main/proto/gravitino_meta.proto b/meta/src/main/proto/gravitino_meta.protoindex 94cccc9185..e160c8eaf0 100644--- a/meta/src/main/proto/gravitino_meta.proto+++ b/meta/src/main/proto/gravitino_meta.proto@@ -105,15 +105,17 @@ message Topic {message User {uint64 id = 1;string name = 2;- repeated string roles = 3;- AuditInfo audit_info = 4;+ repeated string role_names = 3;+ repeated uint64 role_ids = 4;+ AuditInfo audit_info = 5;}message Group {uint64 id = 1;string name = 2;- repeated string roles = 3;- AuditInfo audit_info = 4;+ repeated string role_names = 3;+ repeated uint64 role_ids = 4;+ AuditInfo audit_info = 5;}message Role {diff --git a/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestGroupOperations.java b/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestGroupOperations.javaindex b345427f2e..ecba282167 100644--- a/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestGroupOperations.java+++ b/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestGroupOperations.java@@ -230,7 +230,7 @@ public class TestGroupOperations extends JerseyTest {return GroupEntity.builder().withId(1L).withName(group)- .withRoles(Collections.emptyList())+ .withRoleNames(Collections.emptyList()).withAuditInfo(AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build()).build();diff --git a/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestMetalakeAdminOperations.java b/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestMetalakeAdminOperations.javaindex 0c83c56991..8437626dc1 100644--- a/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestMetalakeAdminOperations.java+++ b/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestMetalakeAdminOperations.java@@ -147,7 +147,7 @@ public class TestMetalakeAdminOperations extends JerseyTest {return UserEntity.builder().withId(1L).withName(user)- .withRoles(Collections.emptyList())+ .withRoleNames(Collections.emptyList()).withAuditInfo(AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build()).build();diff --git a/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestUserOperations.java b/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestUserOperations.javaindex 75c2f142d8..71e00d6f33 100644--- a/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestUserOperations.java+++ b/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestUserOperations.java@@ -231,7 +231,7 @@ public class TestUserOperations extends JerseyTest {return UserEntity.builder().withId(1L).withName(user)- .withRoles(Collections.emptyList())+ .withRoleNames(Collections.emptyList()).withAuditInfo(AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build()).build();