World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#2241] feat(client,server): Support the permission operations for both server and client side. (#3006)
qqqttt123589ac449af12
diff --git a/clients/client-java/src/main/java/com/datastrato/gravitino/client/ErrorHandlers.java b/clients/client-java/src/main/java/com/datastrato/gravitino/client/ErrorHandlers.javaindex d140b0c2a7..9e322fbaf8 100644--- a/clients/client-java/src/main/java/com/datastrato/gravitino/client/ErrorHandlers.java+++ b/clients/client-java/src/main/java/com/datastrato/gravitino/client/ErrorHandlers.java@@ -155,6 +155,14 @@ public class ErrorHandlers {public static Consumer<ErrorResponse> roleErrorHandler() {return RoleErrorHandler.INSTANCE;}+ /**+ * Creates an error handler specific to permission operations.+ *+ * @return A Consumer representing the permission error handler.+ */+ public static Consumer<ErrorResponse> permissionOperationErrorHandler() {+ return PermissionOperationErrorHandler.INSTANCE;+ }private ErrorHandlers() {}@@ -597,6 +605,43 @@ public class ErrorHandlers {}}+ /** Error handler specific to Permission operations. */+ @SuppressWarnings("FormatStringAnnotation")+ private static class PermissionOperationErrorHandler extends RestErrorHandler {++ private static final PermissionOperationErrorHandler INSTANCE =+ new PermissionOperationErrorHandler();++ @Override+ public void accept(ErrorResponse errorResponse) {+ String errorMessage = formatErrorMessage(errorResponse);++ switch (errorResponse.getCode()) {+ case ErrorConstants.ILLEGAL_ARGUMENTS_CODE:+ throw new IllegalArgumentException(errorMessage);++ case ErrorConstants.NOT_FOUND_CODE:+ if (errorResponse.getType().equals(NoSuchMetalakeException.class.getSimpleName())) {+ throw new NoSuchMetalakeException(errorMessage);+ } else if (errorResponse.getType().equals(NoSuchUserException.class.getSimpleName())) {+ throw new NoSuchUserException(errorMessage);+ } else if (errorResponse.getType().equals(NoSuchGroupException.class.getSimpleName())) {+ throw new NoSuchGroupException(errorMessage);+ } else if (errorResponse.getType().equals(NoSuchRoleException.class.getSimpleName())) {+ throw new NoSuchRoleException(errorMessage);+ } else {+ throw new NotFoundException(errorMessage);+ }++ case ErrorConstants.INTERNAL_ERROR_CODE:+ throw new RuntimeException(errorMessage);++ default:+ super.accept(errorResponse);+ }+ }+ }+/** Generic error handler for REST requests. */private static class RestErrorHandler extends ErrorHandler {private static final ErrorHandler INSTANCE = new RestErrorHandler();diff --git a/clients/client-java/src/main/java/com/datastrato/gravitino/client/GravitinoAdminClient.java b/clients/client-java/src/main/java/com/datastrato/gravitino/client/GravitinoAdminClient.javaindex 07675037f2..4cea0f062d 100644--- a/clients/client-java/src/main/java/com/datastrato/gravitino/client/GravitinoAdminClient.java+++ b/clients/client-java/src/main/java/com/datastrato/gravitino/client/GravitinoAdminClient.java@@ -18,6 +18,8 @@ import com.datastrato.gravitino.dto.requests.MetalakeCreateRequest;import com.datastrato.gravitino.dto.requests.MetalakeUpdateRequest;import com.datastrato.gravitino.dto.requests.MetalakeUpdatesRequest;import com.datastrato.gravitino.dto.requests.RoleCreateRequest;+import com.datastrato.gravitino.dto.requests.RoleGrantRequest;+import com.datastrato.gravitino.dto.requests.RoleRevokeRequest;import com.datastrato.gravitino.dto.requests.UserAddRequest;import com.datastrato.gravitino.dto.responses.DeleteResponse;import com.datastrato.gravitino.dto.responses.DropResponse;@@ -58,6 +60,8 @@ public class GravitinoAdminClient extends GravitinoClientBase implements Supportprivate static final String API_METALAKES_GROUPS_PATH = "api/metalakes/%s/groups/%s";private static final String API_METALAKES_ROLES_PATH = "api/metalakes/%s/roles/%s";private static final String API_ADMIN_PATH = "api/admins/%s";+ private static final String API_PERMISSION_PATH = "api/metalakes/%s/permissions/%s";+ private static final String BLANK_PLACE_HOLDER = "";/*** Constructs a new GravitinoClient with the given URI, authenticator and AuthDataProvider.@@ -203,7 +207,7 @@ public class GravitinoAdminClient extends GravitinoClientBase implements SupportUserResponse resp =restClient.post(- String.format(API_METALAKES_USERS_PATH, metalake, ""),+ String.format(API_METALAKES_USERS_PATH, metalake, BLANK_PLACE_HOLDER),req,UserResponse.class,Collections.emptyMap(),@@ -218,7 +222,7 @@ public class GravitinoAdminClient extends GravitinoClientBase implements Support** @param metalake The Metalake of the User.* @param user The name of the User.- * @return `true` if the User was successfully removed, `false` only when there's no such user,+ * @return True if the User was successfully removed, false only when there's no such user,* otherwise it will throw an exception.* @throws NoSuchMetalakeException If the Metalake with the given name does not exist.* @throws RuntimeException If removing the User encounters storage issues.@@ -275,7 +279,7 @@ public class GravitinoAdminClient extends GravitinoClientBase implements SupportGroupResponse resp =restClient.post(- String.format(API_METALAKES_GROUPS_PATH, metalake, ""),+ String.format(API_METALAKES_GROUPS_PATH, metalake, BLANK_PLACE_HOLDER),req,GroupResponse.class,Collections.emptyMap(),@@ -290,7 +294,7 @@ public class GravitinoAdminClient extends GravitinoClientBase implements Support** @param metalake The Metalake of the Group.* @param group THe name of the Group.- * @return `true` if the Group was successfully removed, `false` only when there's no such group,+ * @return True if the Group was successfully removed, false only when there's no such group,* otherwise it will throw an exception.* @throws NoSuchMetalakeException If the Metalake with the given name does not exist.* @throws RuntimeException If removing the Group encounters storage issues.@@ -344,7 +348,7 @@ public class GravitinoAdminClient extends GravitinoClientBase implements SupportUserResponse resp =restClient.post(- String.format(API_ADMIN_PATH, ""),+ String.format(API_ADMIN_PATH, BLANK_PLACE_HOLDER),req,UserResponse.class,Collections.emptyMap(),@@ -358,7 +362,7 @@ public class GravitinoAdminClient extends GravitinoClientBase implements Support* Removes a metalake admin.** @param user The name of the User.- * @return `true` if the User was successfully removed, `false` only when there's no such metalake+ * @return True if the User was successfully removed, false only when there's no such metalake* admin, otherwise it will throw an exception.* @throws RuntimeException If removing the User encounters storage issues.*/@@ -402,7 +406,7 @@ public class GravitinoAdminClient extends GravitinoClientBase implements Support** @param metalake The Metalake of the Role.* @param role The name of the Role.- * @return `true` if the Role was successfully deleted, `false` only when there's no such role,+ * @return True if the Role was successfully deleted, false only when there's no such role,* otherwise it will throw an exception.* @throws NoSuchMetalakeException If the Metalake with the given name does not exist.* @throws RuntimeException If deleting the Role encounters storage issues.@@ -452,7 +456,7 @@ public class GravitinoAdminClient extends GravitinoClientBase implements SupportRoleResponse resp =restClient.post(- String.format(API_METALAKES_ROLES_PATH, metalake, ""),+ String.format(API_METALAKES_ROLES_PATH, metalake, BLANK_PLACE_HOLDER),req,RoleResponse.class,Collections.emptyMap(),@@ -461,6 +465,113 @@ public class GravitinoAdminClient extends GravitinoClientBase implements Supportreturn resp.getRole();}+ /**+ * Grant roles to a user.+ *+ * @param metalake The metalake of the User.+ * @param user The name of the User.+ * @param roles The names of the Role.+ * @return The Group after granted.+ * @throws NoSuchUserException If the User with the given name does not exist.+ * @throws NoSuchRoleException If the Role with the given name does not exist.+ * @throws NoSuchMetalakeException If the Metalake with the given name does not exist.+ * @throws RuntimeException If granting roles to a user encounters storage issues.+ */+ public User grantRolesToUser(String metalake, List<String> roles, String user)+ throws NoSuchUserException, NoSuchRoleException, NoSuchMetalakeException {+ RoleGrantRequest request = new RoleGrantRequest(roles);+ UserResponse resp =+ restClient.put(+ String.format(API_PERMISSION_PATH, metalake, String.format("users/%s/grant", user)),+ request,+ UserResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.permissionOperationErrorHandler());+ resp.validate();++ return resp.getUser();+ }++ /**+ * Grant roles to a group.+ *+ * @param metalake The metalake of the Group.+ * @param group The name of the Group.+ * @param roles The names of the Role.+ * @return The Group after granted.+ * @throws NoSuchGroupException If the Group with the given name does not exist.+ * @throws NoSuchRoleException If the Role with the given name does not exist.+ * @throws NoSuchMetalakeException If the Metalake with the given name does not exist.+ * @throws RuntimeException If granting roles to a group encounters storage issues.+ */+ public Group grantRolesToGroup(String metalake, List<String> roles, String group)+ throws NoSuchGroupException, NoSuchRoleException, NoSuchMetalakeException {+ RoleGrantRequest request = new RoleGrantRequest(roles);+ GroupResponse resp =+ restClient.put(+ String.format(API_PERMISSION_PATH, metalake, String.format("groups/%s/grant", group)),+ request,+ GroupResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.permissionOperationErrorHandler());+ resp.validate();++ return resp.getGroup();+ }++ /**+ * Revoke roles from a user.+ *+ * @param metalake The metalake of the User.+ * @param user The name of the User.+ * @param roles The names of the Role.+ * @return The User after revoked.+ * @throws NoSuchUserException If the User with the given name does not exist.+ * @throws NoSuchRoleException If the Role with the given name does not exist.+ * @throws NoSuchMetalakeException If the Metalake with the given name does not exist.+ * @throws RuntimeException If revoking roles from a user encounters storage issues.+ */+ public User revokeRolesFromUser(String metalake, List<String> roles, String user)+ throws NoSuchUserException, NoSuchRoleException, NoSuchMetalakeException {+ RoleRevokeRequest request = new RoleRevokeRequest(roles);+ UserResponse resp =+ restClient.put(+ String.format(API_PERMISSION_PATH, metalake, String.format("users/%s/revoke", user)),+ request,+ UserResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.permissionOperationErrorHandler());+ resp.validate();++ return resp.getUser();+ }++ /**+ * Revoke roles from a group.+ *+ * @param metalake The metalake of the Group.+ * @param group The name of the Group.+ * @param roles The names of the Role.+ * @return The Group after revoked.+ * @throws NoSuchGroupException If the Group with the given name does not exist.+ * @throws NoSuchRoleException If the Role with the given name does not exist.+ * @throws NoSuchMetalakeException If the Metalake with the given name does not exist.+ * @throws RuntimeException If revoking roles from a group encounters storage issues.+ */+ public Group revokeRolesFromGroup(String metalake, List<String> roles, String group)+ throws NoSuchGroupException, NoSuchRoleException, NoSuchMetalakeException {+ RoleRevokeRequest request = new RoleRevokeRequest(roles);+ GroupResponse resp =+ restClient.put(+ String.format(API_PERMISSION_PATH, metalake, String.format("groups/%s/revoke", group)),+ request,+ GroupResponse.class,+ Collections.emptyMap(),+ ErrorHandlers.permissionOperationErrorHandler());+ resp.validate();++ return resp.getGroup();+ }/*** Creates a new builder for constructing a GravitinoClient.diff --git a/clients/client-java/src/test/java/com/datastrato/gravitino/client/TestPermission.java b/clients/client-java/src/test/java/com/datastrato/gravitino/client/TestPermission.javanew file mode 100644index 0000000000..69ac63c1cc--- /dev/null+++ b/clients/client-java/src/test/java/com/datastrato/gravitino/client/TestPermission.java@@ -0,0 +1,145 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.gravitino.client;++import static javax.servlet.http.HttpServletResponse.SC_OK;+import static org.apache.hc.core5.http.HttpStatus.SC_SERVER_ERROR;++import com.datastrato.gravitino.authorization.Group;+import com.datastrato.gravitino.authorization.User;+import com.datastrato.gravitino.dto.AuditDTO;+import com.datastrato.gravitino.dto.authorization.GroupDTO;+import com.datastrato.gravitino.dto.authorization.UserDTO;+import com.datastrato.gravitino.dto.requests.RoleGrantRequest;+import com.datastrato.gravitino.dto.requests.RoleRevokeRequest;+import com.datastrato.gravitino.dto.responses.ErrorResponse;+import com.datastrato.gravitino.dto.responses.GroupResponse;+import com.datastrato.gravitino.dto.responses.UserResponse;+import com.google.common.collect.Lists;+import java.time.Instant;+import java.util.List;+import org.apache.hc.core5.http.Method;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++public class TestPermission extends TestBase {++ private static final String metalakeName = "testMetalake";+ private static final String API_PERMISSION_PATH = "/api/metalakes/%s/permissions/%s";++ @BeforeAll+ public static void setUp() throws Exception {+ TestBase.setUp();+ }++ @Test+ public void testGrantRolesToUser() throws Exception {+ List<String> roles = Lists.newArrayList("role");+ String user = "user";+ String userPath =+ String.format(API_PERMISSION_PATH, metalakeName, String.format("users/%s/grant", user));+ RoleGrantRequest request = new RoleGrantRequest(roles);+ UserDTO userDTO =+ UserDTO.builder()+ .withName("user")+ .withRoles(Lists.newArrayList("roles"))+ .withAudit(AuditDTO.builder().withCreator("test").withCreateTime(Instant.now()).build())+ .build();+ UserResponse response = new UserResponse(userDTO);++ buildMockResource(Method.PUT, userPath, request, response, SC_OK);+ User grantedUser = client.grantRolesToUser(metalakeName, roles, user);+ Assertions.assertEquals(grantedUser.roles(), userDTO.roles());+ Assertions.assertEquals(grantedUser.name(), userDTO.name());++ // test Exception+ ErrorResponse errResp2 = ErrorResponse.internalError("internal error");+ buildMockResource(Method.PUT, userPath, request, errResp2, SC_SERVER_ERROR);+ Assertions.assertThrows(+ RuntimeException.class, () -> client.grantRolesToUser(metalakeName, roles, user));+ }++ @Test+ public void testRevokeRolesFromUser() throws Exception {+ List<String> roles = Lists.newArrayList("role");+ String user = "user";+ String userPath =+ String.format(API_PERMISSION_PATH, metalakeName, String.format("users/%s/revoke", user));+ UserDTO userDTO =+ UserDTO.builder()+ .withName("user")+ .withRoles(Lists.newArrayList())+ .withAudit(AuditDTO.builder().withCreator("test").withCreateTime(Instant.now()).build())+ .build();+ UserResponse response = new UserResponse(userDTO);+ RoleRevokeRequest request = new RoleRevokeRequest(roles);++ buildMockResource(Method.PUT, userPath, request, response, SC_OK);+ User revokedUser = client.revokeRolesFromUser(metalakeName, roles, user);+ Assertions.assertEquals(revokedUser.roles(), userDTO.roles());+ Assertions.assertEquals(revokedUser.name(), userDTO.name());++ // test Exception+ ErrorResponse errResp2 = ErrorResponse.internalError("internal error");+ buildMockResource(Method.PUT, userPath, null, errResp2, SC_SERVER_ERROR);+ Assertions.assertThrows(+ RuntimeException.class, () -> client.revokeRolesFromUser(metalakeName, roles, user));+ }++ @Test+ public void testGrantRolesToGroup() throws Exception {+ List<String> roles = Lists.newArrayList("role");+ String group = "group";+ String groupPath =+ String.format(API_PERMISSION_PATH, metalakeName, String.format("groups/%s/grant", group));+ RoleGrantRequest request = new RoleGrantRequest(roles);+ GroupDTO groupDTO =+ GroupDTO.builder()+ .withName("group")+ .withRoles(Lists.newArrayList("roles"))+ .withAudit(AuditDTO.builder().withCreator("test").withCreateTime(Instant.now()).build())+ .build();+ GroupResponse response = new GroupResponse(groupDTO);++ buildMockResource(Method.PUT, groupPath, request, response, SC_OK);+ Group grantedGroup = client.grantRolesToGroup(metalakeName, roles, group);+ Assertions.assertEquals(grantedGroup.roles(), groupDTO.roles());+ Assertions.assertEquals(grantedGroup.name(), groupDTO.name());++ // test Exception+ ErrorResponse errResp = ErrorResponse.internalError("internal error");+ buildMockResource(Method.POST, groupPath, request, errResp, SC_SERVER_ERROR);+ Assertions.assertThrows(+ RuntimeException.class, () -> client.grantRolesToGroup(metalakeName, roles, group));+ }++ @Test+ public void testRevokeRoleFromGroup() throws Exception {+ List<String> roles = Lists.newArrayList("role");+ String group = "group";+ String groupPath =+ String.format(API_PERMISSION_PATH, metalakeName, String.format("groups/%s/revoke", group));+ GroupDTO groupDTO =+ GroupDTO.builder()+ .withName("group")+ .withRoles(Lists.newArrayList())+ .withAudit(AuditDTO.builder().withCreator("test").withCreateTime(Instant.now()).build())+ .build();+ GroupResponse response = new GroupResponse(groupDTO);+ RoleRevokeRequest request = new RoleRevokeRequest(roles);++ buildMockResource(Method.PUT, groupPath, request, response, SC_OK);+ Group revokedGroup = client.revokeRolesFromGroup(metalakeName, roles, group);+ Assertions.assertEquals(revokedGroup.roles(), groupDTO.roles());+ Assertions.assertEquals(revokedGroup.name(), groupDTO.name());++ // test Exception+ ErrorResponse errResp = ErrorResponse.internalError("internal error");+ buildMockResource(Method.DELETE, groupPath, null, errResp, SC_SERVER_ERROR);+ Assertions.assertThrows(+ RuntimeException.class, () -> client.revokeRolesFromGroup(metalakeName, roles, group));+ }+}diff --git a/common/src/main/java/com/datastrato/gravitino/dto/requests/RoleGrantRequest.java b/common/src/main/java/com/datastrato/gravitino/dto/requests/RoleGrantRequest.javanew file mode 100644index 0000000000..2bd6880ee2--- /dev/null+++ b/common/src/main/java/com/datastrato/gravitino/dto/requests/RoleGrantRequest.java@@ -0,0 +1,52 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.gravitino.dto.requests;++import com.datastrato.gravitino.rest.RESTRequest;+import com.fasterxml.jackson.annotation.JsonProperty;+import com.google.common.base.Preconditions;+import java.util.List;+import lombok.Builder;+import lombok.EqualsAndHashCode;+import lombok.Getter;+import lombok.ToString;+import lombok.extern.jackson.Jacksonized;++/** Represents a request to grant roles to the user or the group. */+@Getter+@EqualsAndHashCode+@ToString+@Builder+@Jacksonized+public class RoleGrantRequest implements RESTRequest {+ @JsonProperty("roleNames")+ private final List<String> roleNames;++ /**+ * Constructor for RoleGrantRequest.+ *+ * @param roleNames The roleName for the RoleGrantRequest.+ */+ public RoleGrantRequest(List<String> roleNames) {+ this.roleNames = roleNames;+ }++ /** Default constructor for RoleGrantRequest. */+ public RoleGrantRequest() {+ this(null);+ }++ /**+ * Validates the fields of the request.+ *+ * @throws IllegalArgumentException if the role names is not set or empty.+ */+ @Override+ public void validate() throws IllegalArgumentException {+ Preconditions.checkArgument(+ roleNames != null && !roleNames.isEmpty(),+ "\"roleName\" field is required and cannot be empty");+ }+}diff --git a/common/src/main/java/com/datastrato/gravitino/dto/requests/RoleRevokeRequest.java b/common/src/main/java/com/datastrato/gravitino/dto/requests/RoleRevokeRequest.javanew file mode 100644index 0000000000..02f3a3ac31--- /dev/null+++ b/common/src/main/java/com/datastrato/gravitino/dto/requests/RoleRevokeRequest.java@@ -0,0 +1,52 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.gravitino.dto.requests;++import com.datastrato.gravitino.rest.RESTRequest;+import com.fasterxml.jackson.annotation.JsonProperty;+import com.google.common.base.Preconditions;+import java.util.List;+import lombok.Builder;+import lombok.EqualsAndHashCode;+import lombok.Getter;+import lombok.ToString;+import lombok.extern.jackson.Jacksonized;++/** Represents a request to revoke roles from the user or the group. */+@Getter+@EqualsAndHashCode+@ToString+@Builder+@Jacksonized+public class RoleRevokeRequest implements RESTRequest {+ @JsonProperty("roleNames")+ private final List<String> roleNames;++ /**+ * Constructor for RoleRevokeRequest.+ *+ * @param roleNames The roleName for the RoleRevokeRequest.+ */+ public RoleRevokeRequest(List<String> roleNames) {+ this.roleNames = roleNames;+ }++ /** Default constructor for RoleRevokeRequest. */+ public RoleRevokeRequest() {+ this(null);+ }++ /**+ * Validates the fields of the request.+ *+ * @throws IllegalArgumentException if the role names is not set or empty.+ */+ @Override+ public void validate() throws IllegalArgumentException {+ Preconditions.checkArgument(+ roleNames != null && !roleNames.isEmpty(),+ "\"roleName\" field is required and cannot be empty");+ }+}diff --git a/core/src/main/java/com/datastrato/gravitino/authorization/AccessControlManager.java b/core/src/main/java/com/datastrato/gravitino/authorization/AccessControlManager.javaindex 35c3ea99f4..5f1843614f 100644--- a/core/src/main/java/com/datastrato/gravitino/authorization/AccessControlManager.java+++ b/core/src/main/java/com/datastrato/gravitino/authorization/AccessControlManager.java@@ -63,7 +63,7 @@ public class AccessControlManager {** @param metalake The Metalake of the User.* @param user The name of the User.- * @return `true` if the User was successfully removed, `false` only when there's no such user,+ * @return True if the User was successfully removed, false only when there's no such user,* otherwise it will throw an exception.* @throws NoSuchMetalakeException If the Metalake with the given name does not exist.* @throws RuntimeException If removing the User encounters storage issues.@@ -107,7 +107,7 @@ public class AccessControlManager {** @param metalake The Metalake of the Group.* @param group THe name of the Group.- * @return `true` if the Group was successfully removed, `false` only when there's no such group,+ * @return True if the Group was successfully removed, false only when there's no such group,* otherwise it will throw an exception.* @throws NoSuchMetalakeException If the Metalake with the given name does not exist.* @throws RuntimeException If removing the Group encounters storage issues.@@ -132,67 +132,71 @@ public class AccessControlManager {}/**- * Grant a role to a user.+ * Grant roles 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.+ * @param roles The names of the Role.+ * @return The User after granted.+ * @throws NoSuchUserException If the User with the given name does not exist.+ * @throws NoSuchRoleException If the Role with the given name does not exist.+ * @throws NoSuchMetalakeException If the Metalake with the given name does not exist.+ * @throws RuntimeException If granting roles to a user encounters storage issues.*/- public boolean grantRoleToUser(String metalake, String role, String user) {- return doWithNonAdminLock(() -> permissionManager.grantRoleToUser(metalake, role, user));+ public User grantRolesToUser(String metalake, List<String> roles, String user)+ throws NoSuchUserException, NoSuchRoleException, NoSuchMetalakeException {+ return doWithNonAdminLock(() -> permissionManager.grantRolesToUser(metalake, roles, user));}/**- * Grant a role to a group.+ * Grant roles 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.+ * @param group The name of the Group.+ * @param roles The names of the Role.+ * @return The Group after granted.+ * @throws NoSuchGroupException If the Group with the given name does not exist.+ * @throws NoSuchRoleException If the Role with the given name does not exist.+ * @throws NoSuchMetalakeException If the Metalake with the given name does not exist.+ * @throws RuntimeException If granting roles to a group encounters storage issues.*/- public boolean grantRoleToGroup(String metalake, String role, String group) {- return doWithNonAdminLock(() -> permissionManager.grantRoleToGroup(metalake, role, group));+ public Group grantRolesToGroup(String metalake, List<String> roles, String group)+ throws NoSuchGroupException, NoSuchRoleException, NoSuchMetalakeException {+ return doWithNonAdminLock(() -> permissionManager.grantRolesToGroup(metalake, roles, group));}/**- * Revoke a role from a group.+ * Revoke roles 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.+ * @param roles The name of the Role.+ * @return The Group after revoked.+ * @throws NoSuchGroupException If the Group with the given name does not exist.+ * @throws NoSuchRoleException If the Role with the given name does not exist.+ * @throws NoSuchMetalakeException If the Metalake with the given name does not exist.+ * @throws RuntimeException If revoking roles from a group encounters storage issues.*/- public boolean revokeRoleFromGroup(String metalake, String role, String group) {- return doWithNonAdminLock(() -> permissionManager.revokeRoleFromGroup(metalake, role, group));+ public Group revokeRolesFromGroup(String metalake, List<String> roles, String group)+ throws NoSuchGroupException, NoSuchRoleException, NoSuchMetalakeException {+ return doWithNonAdminLock(() -> permissionManager.revokeRolesFromGroup(metalake, roles, group));}/**- * Revoke a role from a user.+ * Revoke roles 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.+ * @param roles The name of the Role.+ * @return The User after revoked.+ * @throws NoSuchUserException If the User with the given name does not exist.+ * @throws NoSuchRoleException If the Role with the given name does not exist.+ * @throws NoSuchMetalakeException If the Metalake with the given name does not exist.+ * @throws RuntimeException If revoking roles from a user encounters storage issues.*/- public boolean revokeRoleFromUser(String metalake, String role, String user) {- return doWithNonAdminLock(() -> permissionManager.revokeRoleFromUser(metalake, role, user));+ public User revokeRolesFromUser(String metalake, List<String> roles, String user)+ throws NoSuchUserException, NoSuchRoleException, NoSuchMetalakeException {+ return doWithNonAdminLock(() -> permissionManager.revokeRolesFromUser(metalake, roles, user));}/**@@ -211,7 +215,7 @@ public class AccessControlManager {* Removes a metalake admin.** @param user The name of the User.- * @return `true` if the User was successfully removed, `false` only when there's no such metalake+ * @return True if the User was successfully removed, false only when there's no such metalake* admin, otherwise it will throw an exception.* @throws RuntimeException If removing the User encounters storage issues.*/@@ -223,7 +227,7 @@ public class AccessControlManager {* 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.+ * @return True if the user is service admin, otherwise false.*/public boolean isServiceAdmin(String user) {return adminManager.isServiceAdmin(user);@@ -233,7 +237,7 @@ public class AccessControlManager {* 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.+ * @return True if the user is metalake admin, otherwise false.*/public boolean isMetalakeAdmin(String user) {return doWithAdminLock(() -> adminManager.isMetalakeAdmin(user));@@ -283,7 +287,7 @@ public class AccessControlManager {** @param metalake The Metalake of the Role.* @param role The name of the Role.- * @return `true` if the Role was successfully deleted, `false` only when there's no such role,+ * @return True if the Role was successfully deleted, false only when there's no such role,* otherwise it will throw an exception.* @throws NoSuchMetalakeException If the Metalake with the given name does not exist.* @throws RuntimeException If deleting the Role encounters storage issues.diff --git a/core/src/main/java/com/datastrato/gravitino/authorization/PermissionManager.java b/core/src/main/java/com/datastrato/gravitino/authorization/PermissionManager.javaindex a77eb19133..c8e6060ab5 100644--- a/core/src/main/java/com/datastrato/gravitino/authorization/PermissionManager.java+++ b/core/src/main/java/com/datastrato/gravitino/authorization/PermissionManager.java@@ -12,7 +12,6 @@ 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;@@ -22,8 +21,8 @@ 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.apache.commons.lang3.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -42,11 +41,14 @@ class PermissionManager {this.roleManager = roleManager;}- boolean grantRoleToUser(String metalake, String role, String user) {+ User grantRolesToUser(String metalake, List<String> roles, String user) {try {- RoleEntity roleEntity = roleManager.getRole(metalake, role);+ List<RoleEntity> roleEntitiesToGrant = Lists.newArrayList();+ for (String role : roles) {+ roleEntitiesToGrant.add(roleManager.getRole(metalake, role));+ }- store.update(+ return store.update(AuthorizationUtils.ofUser(metalake, user),UserEntity.class,Entity.EntityType.USER,@@ -57,13 +59,19 @@ class PermissionManager {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);+ for (RoleEntity roleEntityToGrant : roleEntitiesToGrant) {+ if (roleNames.contains(roleEntityToGrant.name())) {+ LOG.warn(+ "Failed to grant, role {} already exists in the user {} of metalake {}",+ roleEntityToGrant.name(),+ user,+ metalake);+ } else {+ roleNames.add(roleEntityToGrant.name());+ roleIds.add(roleEntityToGrant.id());+ }}- roleNames.add(roleEntity.name());- roleIds.add(roleEntity.id());AuditInfo auditInfo =AuditInfo.builder().withCreator(userEntity.auditInfo().creator())@@ -81,14 +89,13 @@ class PermissionManager {.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,+ StringUtils.join(roles, ","),user,metalake,ioe);@@ -96,11 +103,14 @@ class PermissionManager {}}- boolean grantRoleToGroup(String metalake, String role, String group) {+ Group grantRolesToGroup(String metalake, List<String> roles, String group) {try {- RoleEntity roleEntity = roleManager.getRole(metalake, role);+ List<RoleEntity> roleEntitiesToGrant = Lists.newArrayList();+ for (String role : roles) {+ roleEntitiesToGrant.add(roleManager.getRole(metalake, role));+ }- store.update(+ return store.update(AuthorizationUtils.ofGroup(metalake, group),GroupEntity.class,Entity.EntityType.GROUP,@@ -110,10 +120,17 @@ class PermissionManager {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);+ for (RoleEntity roleEntityToGrant : roleEntitiesToGrant) {+ if (roleNames.contains(roleEntityToGrant.name())) {+ LOG.warn(+ "Failed to grant, role {} already exists in the group {} of metalake {}",+ roleEntityToGrant.name(),+ group,+ metalake);+ } else {+ roleNames.add(roleEntityToGrant.name());+ roleIds.add(roleEntityToGrant.id());+ }}AuditInfo auditInfo =@@ -124,8 +141,6 @@ class PermissionManager {.withLastModifiedTime(Instant.now()).build();- roleNames.add(roleEntity.name());- roleIds.add(roleEntity.id());return GroupEntity.builder().withId(groupEntity.id()).withNamespace(groupEntity.namespace())@@ -135,14 +150,13 @@ class PermissionManager {.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,+ StringUtils.join(roles, ","),group,metalake,ioe);@@ -150,13 +164,14 @@ class PermissionManager {}}- boolean revokeRoleFromGroup(String metalake, String role, String group) {+ Group revokeRolesFromGroup(String metalake, List<String> roles, String group) {try {- RoleEntity roleEntity = roleManager.getRole(metalake, role);+ List<RoleEntity> roleEntitiesToRevoke = Lists.newArrayList();+ for (String role : roles) {+ roleEntitiesToRevoke.add(roleManager.getRole(metalake, role));+ }- AtomicBoolean removed = new AtomicBoolean(true);-- store.update(+ return store.update(AuthorizationUtils.ofGroup(metalake, group),GroupEntity.class,Entity.EntityType.GROUP,@@ -165,15 +180,17 @@ class PermissionManager {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);+ for (RoleEntity roleEntityToRevoke : roleEntitiesToRevoke) {+ roleNames.remove(roleEntityToRevoke.name());+ boolean removed = roleIds.remove(roleEntityToRevoke.id());+ if (!removed) {+ LOG.warn(+ "Failed to revoke, role {} does not exist in the group {} of metalake {}",+ roleEntityToRevoke.name(),+ group,+ metalake);+ }}AuditInfo auditInfo =@@ -194,7 +211,6 @@ class PermissionManager {.build();});- return removed.get();} catch (NoSuchEntityException nse) {LOG.warn("Failed to revoke, group {} does not exist in the metalake {}", group, metalake, nse);@@ -202,7 +218,7 @@ class PermissionManager {} catch (IOException ioe) {LOG.error("Failed to revoke role {} from group {} in the metalake {} due to storage issues",- role,+ StringUtils.join(roles, ","),group,metalake,ioe);@@ -210,12 +226,14 @@ class PermissionManager {}}- boolean revokeRoleFromUser(String metalake, String role, String user) {+ User revokeRolesFromUser(String metalake, List<String> roles, String user) {try {- RoleEntity roleEntity = roleManager.getRole(metalake, role);- AtomicBoolean removed = new AtomicBoolean(true);+ List<RoleEntity> roleEntitiesToRevoke = Lists.newArrayList();+ for (String role : roles) {+ roleEntitiesToRevoke.add(roleManager.getRole(metalake, role));+ }- store.update(+ return store.update(AuthorizationUtils.ofUser(metalake, user),UserEntity.class,Entity.EntityType.USER,@@ -226,14 +244,16 @@ class PermissionManager {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);+ for (RoleEntity roleEntityToRevoke : roleEntitiesToRevoke) {+ roleNames.remove(roleEntityToRevoke.name());+ boolean removed = roleIds.remove(roleEntityToRevoke.id());+ if (!removed) {+ LOG.warn(+ "Failed to revoke, role {} doesn't exist in the user {} of metalake {}",+ roleEntityToRevoke.name(),+ user,+ metalake);+ }}AuditInfo auditInfo =@@ -252,14 +272,13 @@ class PermissionManager {.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,+ StringUtils.join(roles, ","),user,metalake,ioe);diff --git a/core/src/test/java/com/datastrato/gravitino/authorization/TestAccessControlManagerForPermissions.java b/core/src/test/java/com/datastrato/gravitino/authorization/TestAccessControlManagerForPermissions.javaindex cf38825fe3..4d1080649a 100644--- a/core/src/test/java/com/datastrato/gravitino/authorization/TestAccessControlManagerForPermissions.java+++ b/core/src/test/java/com/datastrato/gravitino/authorization/TestAccessControlManagerForPermissions.java@@ -13,7 +13,6 @@ 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;@@ -26,6 +25,7 @@ import com.google.common.collect.Lists;import com.google.common.collect.Maps;import java.io.IOException;import java.time.Instant;+import java.util.List;import org.junit.jupiter.api.AfterAll;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.BeforeAll;@@ -46,7 +46,7 @@ public class TestAccessControlManagerForPermissions {private static String GROUP = "group";- private static String ROLE = "role";+ private static List<String> ROLE = Lists.newArrayList("role");private static AuditInfo auditInfo =AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build();@@ -82,7 +82,7 @@ public class TestAccessControlManagerForPermissions {.withNamespace(Namespace.of(METALAKE, Entity.SYSTEM_CATALOG_RESERVED_NAME, Entity.ROLE_SCHEMA_NAME)).withId(1L)- .withName(ROLE)+ .withName("role").withProperties(Maps.newHashMap()).withPrivileges(Lists.newArrayList(Privileges.LoadCatalog.get())).withSecurableObject(SecurableObjects.of(CATALOG))@@ -123,59 +123,66 @@ public class TestAccessControlManagerForPermissions {User user = accessControlManager.getUser(METALAKE, USER);Assertions.assertTrue(user.roles().isEmpty());- Assertions.assertTrue(accessControlManager.grantRoleToUser(METALAKE, ROLE, USER));+ user = accessControlManager.grantRolesToUser(METALAKE, ROLE, USER);+ Assertions.assertFalse(user.roles().isEmpty());+user = accessControlManager.getUser(METALAKE, USER);Assertions.assertEquals(1, user.roles().size());- Assertions.assertEquals(ROLE, user.roles().get(0));+ Assertions.assertEquals(ROLE, user.roles());- // Throw RoleAlreadyExistsException- Assertions.assertThrows(- RoleAlreadyExistsException.class,- () -> accessControlManager.grantRoleToUser(METALAKE, ROLE, USER));+ // Test with a role which exists+ user = accessControlManager.grantRolesToUser(METALAKE, ROLE, USER);+ Assertions.assertEquals(1, user.roles().size());// Throw NoSuchMetalakeExceptionAssertions.assertThrows(NoSuchMetalakeException.class,- () -> accessControlManager.grantRoleToUser(notExist, ROLE, USER));+ () -> accessControlManager.grantRolesToUser(notExist, ROLE, USER));// Throw NoSuchRoleExceptionAssertions.assertThrows(NoSuchRoleException.class,- () -> accessControlManager.grantRoleToUser(METALAKE, notExist, USER));+ () -> accessControlManager.grantRolesToUser(METALAKE, Lists.newArrayList(notExist), USER));// Throw NoSuchUserExceptionAssertions.assertThrows(NoSuchUserException.class,- () -> accessControlManager.grantRoleToUser(METALAKE, ROLE, notExist));+ () -> accessControlManager.grantRolesToUser(METALAKE, Lists.newArrayList(ROLE), notExist));// Clear Resource- Assertions.assertTrue(accessControlManager.revokeRoleFromUser(METALAKE, ROLE, USER));+ user = accessControlManager.revokeRolesFromUser(METALAKE, Lists.newArrayList(ROLE), USER);+ Assertions.assertTrue(user.roles().isEmpty());}@Testpublic void testRevokeRoleFromUser() {String notExist = "not-exist";- Assertions.assertTrue(accessControlManager.grantRoleToUser(METALAKE, ROLE, USER));- Assertions.assertTrue(accessControlManager.revokeRoleFromUser(METALAKE, ROLE, USER));+ User user = accessControlManager.grantRolesToUser(METALAKE, ROLE, USER);+ Assertions.assertFalse(user.roles().isEmpty());++ user = accessControlManager.revokeRolesFromUser(METALAKE, ROLE, USER);+ Assertions.assertTrue(user.roles().isEmpty());// Throw NoSuchMetalakeExceptionAssertions.assertThrows(NoSuchMetalakeException.class,- () -> accessControlManager.revokeRoleFromUser(notExist, ROLE, USER));+ () -> accessControlManager.revokeRolesFromUser(notExist, ROLE, USER));// Throw NoSuchRoleExceptionAssertions.assertThrows(NoSuchRoleException.class,- () -> accessControlManager.revokeRoleFromUser(METALAKE, notExist, USER));+ () ->+ accessControlManager.revokeRolesFromUser(METALAKE, Lists.newArrayList(notExist), USER));// Remove role which doesn't exist.- Assertions.assertFalse(accessControlManager.revokeRoleFromUser(METALAKE, ROLE, USER));+ user = accessControlManager.revokeRolesFromUser(METALAKE, ROLE, USER);+ Assertions.assertTrue(user.roles().isEmpty());// Throw NoSuchUserExceptionAssertions.assertThrows(NoSuchUserException.class,- () -> accessControlManager.revokeRoleFromUser(METALAKE, ROLE, notExist));+ () -> accessControlManager.revokeRolesFromUser(METALAKE, ROLE, notExist));}@Test@@ -185,60 +192,68 @@ public class TestAccessControlManagerForPermissions {Group group = accessControlManager.getGroup(METALAKE, GROUP);Assertions.assertTrue(group.roles().isEmpty());- Assertions.assertTrue(accessControlManager.grantRoleToGroup(METALAKE, ROLE, GROUP));+ group = accessControlManager.grantRolesToGroup(METALAKE, ROLE, GROUP);+ Assertions.assertFalse(group.roles().isEmpty());group = accessControlManager.getGroup(METALAKE, GROUP);Assertions.assertEquals(1, group.roles().size());- Assertions.assertEquals(ROLE, group.roles().get(0));+ Assertions.assertEquals(ROLE, group.roles());- // Throw RoleAlreadyExistsException- Assertions.assertThrows(- RoleAlreadyExistsException.class,- () -> accessControlManager.grantRoleToGroup(METALAKE, ROLE, GROUP));+ // Test with a role which exists+ group = accessControlManager.grantRolesToGroup(METALAKE, ROLE, GROUP);+ Assertions.assertEquals(1, group.roles().size());// Throw NoSuchMetalakeExceptionAssertions.assertThrows(NoSuchMetalakeException.class,- () -> accessControlManager.grantRoleToGroup(notExist, ROLE, GROUP));+ () -> accessControlManager.grantRolesToGroup(notExist, ROLE, GROUP));// Throw NoSuchRoleExceptionAssertions.assertThrows(NoSuchRoleException.class,- () -> accessControlManager.grantRoleToGroup(METALAKE, notExist, GROUP));+ () ->+ accessControlManager.grantRolesToGroup(METALAKE, Lists.newArrayList(notExist), GROUP));// Throw NoSuchGroupExceptionAssertions.assertThrows(NoSuchGroupException.class,- () -> accessControlManager.grantRoleToGroup(METALAKE, ROLE, notExist));+ () -> accessControlManager.grantRolesToGroup(METALAKE, ROLE, notExist));// Clear Resource- Assertions.assertTrue(accessControlManager.revokeRoleFromGroup(METALAKE, ROLE, GROUP));+ group = accessControlManager.revokeRolesFromGroup(METALAKE, ROLE, GROUP);+ Assertions.assertTrue(group.roles().isEmpty());}@Testpublic void testRevokeRoleFormGroup() {String notExist = "not-exist";- Assertions.assertTrue(accessControlManager.grantRoleToGroup(METALAKE, ROLE, GROUP));- Assertions.assertTrue(accessControlManager.revokeRoleFromGroup(METALAKE, ROLE, GROUP));+ Group group = accessControlManager.grantRolesToGroup(METALAKE, ROLE, GROUP);+ Assertions.assertFalse(group.roles().isEmpty());++ group = accessControlManager.revokeRolesFromGroup(METALAKE, ROLE, GROUP);+ Assertions.assertTrue(group.roles().isEmpty());// Throw NoSuchMetalakeExceptionAssertions.assertThrows(NoSuchMetalakeException.class,- () -> accessControlManager.revokeRoleFromGroup(notExist, ROLE, GROUP));+ () -> accessControlManager.revokeRolesFromGroup(notExist, ROLE, GROUP));// Throw NoSuchRoleExceptionAssertions.assertThrows(NoSuchRoleException.class,- () -> accessControlManager.revokeRoleFromGroup(METALAKE, notExist, USER));+ () ->+ accessControlManager.revokeRolesFromGroup(+ METALAKE, Lists.newArrayList(notExist), GROUP));// Remove not exist role- Assertions.assertFalse(accessControlManager.revokeRoleFromUser(METALAKE, ROLE, USER));+ group = accessControlManager.revokeRolesFromGroup(METALAKE, ROLE, GROUP);+ Assertions.assertTrue(group.roles().isEmpty());// Throw NoSuchGroupExceptionAssertions.assertThrows(NoSuchGroupException.class,- () -> accessControlManager.revokeRoleFromGroup(METALAKE, ROLE, notExist));+ () -> accessControlManager.revokeRolesFromGroup(METALAKE, ROLE, notExist));}@Test@@ -259,10 +274,17 @@ public class TestAccessControlManagerForPermissions {.build();entityStore.put(roleEntity, true);- Assertions.assertTrue(accessControlManager.grantRoleToUser(METALAKE, anotherRole, USER));- Assertions.assertTrue(accessControlManager.grantRoleToGroup(METALAKE, anotherRole, GROUP));- accessControlManager.deleteRole(METALAKE, anotherRole);- Group group = accessControlManager.getGroup(METALAKE, GROUP);++ User user =+ accessControlManager.grantRolesToUser(METALAKE, Lists.newArrayList(anotherRole), USER);+ Assertions.assertFalse(user.roles().isEmpty());++ Group group =+ accessControlManager.grantRolesToGroup(METALAKE, Lists.newArrayList(anotherRole), GROUP);+ Assertions.assertFalse(group.roles().isEmpty());++ Assertions.assertTrue(accessControlManager.deleteRole(METALAKE, anotherRole));+ group = accessControlManager.getGroup(METALAKE, GROUP);Assertions.assertTrue(group.roles().isEmpty());}}diff --git a/server/build.gradle.kts b/server/build.gradle.ktsindex bdd557ec5a..8cfc757cab 100644--- a/server/build.gradle.kts+++ b/server/build.gradle.kts@@ -17,6 +17,7 @@ dependencies {implementation(libs.bundles.jetty)implementation(libs.bundles.jersey)implementation(libs.bundles.log4j)+ implementation(libs.commons.lang3)implementation(libs.guava)implementation(libs.jackson.annotations)implementation(libs.jackson.datatype.jdk8)diff --git a/server/src/main/java/com/datastrato/gravitino/server/web/rest/ExceptionHandlers.java b/server/src/main/java/com/datastrato/gravitino/server/web/rest/ExceptionHandlers.javaindex 130c6f2fa8..c51c666b79 100644--- a/server/src/main/java/com/datastrato/gravitino/server/web/rest/ExceptionHandlers.java+++ b/server/src/main/java/com/datastrato/gravitino/server/web/rest/ExceptionHandlers.java@@ -79,6 +79,16 @@ public class ExceptionHandlers {return TopicExceptionHandler.INSTANCE.handle(op, topic, schema, e);}+ public static Response handleUserPermissionOperationException(+ OperationType op, String roles, String parent, Exception e) {+ return UserPermissionOperationExceptionHandler.INSTANCE.handle(op, roles, parent, e);+ }++ public static Response handleGroupPermissionOperationException(+ OperationType op, String roles, String parent, Exception e) {+ return GroupPermissionOperationExceptionHandler.INSTANCE.handle(op, roles, parent, e);+ }+private static class PartitionExceptionHandler extends BaseExceptionHandler {private static final ExceptionHandler INSTANCE = new PartitionExceptionHandler();@@ -414,6 +424,56 @@ public class ExceptionHandlers {}}+ private static class UserPermissionOperationExceptionHandler+ extends BasePermissionExceptionHandler {+ private static final ExceptionHandler INSTANCE = new UserPermissionOperationExceptionHandler();++ @Override+ protected String getPermissionErrorMsg(+ String role, String operation, String parent, String reason) {+ return String.format(+ "Failed to operate role(s)%s operation [%s] under user [%s], reason [%s]",+ role, operation, parent, reason);+ }+ }++ private static class GroupPermissionOperationExceptionHandler+ extends BasePermissionExceptionHandler {++ private static final ExceptionHandler INSTANCE = new GroupPermissionOperationExceptionHandler();++ @Override+ protected String getPermissionErrorMsg(+ String roles, String operation, String parent, String reason) {+ return String.format(+ "Failed to operate role(s)%s operation [%s] under group [%s], reason [%s]",+ roles, operation, parent, reason);+ }+ }++ private abstract static class BasePermissionExceptionHandler extends BaseExceptionHandler {++ protected abstract String getPermissionErrorMsg(+ String role, String operation, String parent, String reason);++ @Override+ public Response handle(OperationType op, String roles, String parent, Exception e) {+ String formatted = StringUtil.isBlank(roles) ? "" : " [" + roles + "]";+ String errorMsg = getPermissionErrorMsg(formatted, op.name(), parent, getErrorMsg(e));+ LOG.warn(errorMsg, e);++ if (e instanceof IllegalArgumentException) {+ return Utils.illegalArguments(errorMsg, e);++ } else if (e instanceof NotFoundException) {+ return Utils.notFound(errorMsg, e);++ } else {+ return super.handle(op, roles, parent, e);+ }+ }+ }+@VisibleForTestingstatic class BaseExceptionHandler extends ExceptionHandler {diff --git a/server/src/main/java/com/datastrato/gravitino/server/web/rest/OperationType.java b/server/src/main/java/com/datastrato/gravitino/server/web/rest/OperationType.javaindex 6daacfc822..7649f43b33 100644--- a/server/src/main/java/com/datastrato/gravitino/server/web/rest/OperationType.java+++ b/server/src/main/java/com/datastrato/gravitino/server/web/rest/OperationType.java@@ -14,5 +14,7 @@ public enum OperationType {GET,ADD,REMOVE,- DELETE+ DELETE,+ GRANT,+ REVOKE}diff --git a/server/src/main/java/com/datastrato/gravitino/server/web/rest/PermissionOperations.java b/server/src/main/java/com/datastrato/gravitino/server/web/rest/PermissionOperations.javanew file mode 100644index 0000000000..95b973cc47--- /dev/null+++ b/server/src/main/java/com/datastrato/gravitino/server/web/rest/PermissionOperations.java@@ -0,0 +1,136 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.gravitino.server.web.rest;++import com.codahale.metrics.annotation.ResponseMetered;+import com.codahale.metrics.annotation.Timed;+import com.datastrato.gravitino.GravitinoEnv;+import com.datastrato.gravitino.authorization.AccessControlManager;+import com.datastrato.gravitino.dto.requests.RoleGrantRequest;+import com.datastrato.gravitino.dto.requests.RoleRevokeRequest;+import com.datastrato.gravitino.dto.responses.GroupResponse;+import com.datastrato.gravitino.dto.responses.UserResponse;+import com.datastrato.gravitino.dto.util.DTOConverters;+import com.datastrato.gravitino.metrics.MetricNames;+import com.datastrato.gravitino.server.web.Utils;+import javax.servlet.http.HttpServletRequest;+import javax.ws.rs.PUT;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.core.Context;+import javax.ws.rs.core.Response;+import org.apache.commons.lang3.StringUtils;++@Path("/metalakes/{metalake}/permissions")+public class PermissionOperations {++ private final AccessControlManager accessControlManager;++ @Context private HttpServletRequest httpRequest;++ public PermissionOperations() {+ // Because accessManager may be null when Gravitino doesn't enable authorization,+ // and Jersey injection doesn't support null value. So PermissionOperations chooses to retrieve+ // accessControlManager from GravitinoEnv instead of injection here.+ this.accessControlManager = GravitinoEnv.getInstance().accessControlManager();+ }++ @PUT+ @Path("users/{user}/grant/")+ @Produces("application/vnd.gravitino.v1+json")+ @Timed(name = "grant-roles-to-user." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)+ @ResponseMetered(name = "grant-roles-to-user", absolute = true)+ public Response grantRolesToUser(+ @PathParam("metalake") String metalake,+ @PathParam("user") String user,+ RoleGrantRequest request) {+ try {+ return Utils.doAs(+ httpRequest,+ () ->+ Utils.ok(+ new UserResponse(+ DTOConverters.toDTO(+ accessControlManager.grantRolesToUser(+ metalake, request.getRoleNames(), user)))));+ } catch (Exception e) {+ return ExceptionHandlers.handleUserPermissionOperationException(+ OperationType.GRANT, StringUtils.join(request.getRoleNames(), ","), user, e);+ }+ }++ @PUT+ @Path("groups/{group}/grant/")+ @Produces("application/vnd.gravitino.v1+json")+ @Timed(name = "grant-roles-to-group." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)+ @ResponseMetered(name = "grant-roles-to-group", absolute = true)+ public Response grantRolesToGroup(+ @PathParam("metalake") String metalake,+ @PathParam("group") String group,+ RoleGrantRequest request) {+ try {+ return Utils.doAs(+ httpRequest,+ () ->+ Utils.ok(+ new GroupResponse(+ DTOConverters.toDTO(+ accessControlManager.grantRolesToGroup(+ metalake, request.getRoleNames(), group)))));+ } catch (Exception e) {+ return ExceptionHandlers.handleGroupPermissionOperationException(+ OperationType.GRANT, StringUtils.join(request.getRoleNames(), ","), group, e);+ }+ }++ @PUT+ @Path("users/{user}/revoke/")+ @Produces("application/vnd.gravitino.v1+json")+ @Timed(name = "revoke-roles-from-user." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)+ @ResponseMetered(name = "revoke-roles-from-user", absolute = true)+ public Response revokeRolesFromUser(+ @PathParam("metalake") String metalake,+ @PathParam("user") String user,+ RoleRevokeRequest request) {+ try {+ return Utils.doAs(+ httpRequest,+ () ->+ Utils.ok(+ new UserResponse(+ DTOConverters.toDTO(+ accessControlManager.revokeRolesFromUser(+ metalake, request.getRoleNames(), user)))));+ } catch (Exception e) {+ return ExceptionHandlers.handleUserPermissionOperationException(+ OperationType.REVOKE, StringUtils.join(request.getRoleNames(), ","), user, e);+ }+ }++ @PUT+ @Path("groups/{group}/revoke")+ @Produces("application/vnd.gravitino.v1+json")+ @Timed(name = "revoke-roles-from-group." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)+ @ResponseMetered(name = "revokes-role-from-group", absolute = true)+ public Response revokeRolesFromGroup(+ @PathParam("metalake") String metalake,+ @PathParam("group") String group,+ RoleRevokeRequest request) {+ try {+ return Utils.doAs(+ httpRequest,+ () ->+ Utils.ok(+ new GroupResponse(+ DTOConverters.toDTO(+ accessControlManager.revokeRolesFromGroup(+ metalake, request.getRoleNames(), group)))));+ } catch (Exception e) {+ return ExceptionHandlers.handleGroupPermissionOperationException(+ OperationType.REVOKE, StringUtils.join(request.getRoleNames()), group, e);+ }+ }+}diff --git a/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestPermissionOperations.java b/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestPermissionOperations.javanew file mode 100644index 0000000000..9e8ee453b7--- /dev/null+++ b/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestPermissionOperations.java@@ -0,0 +1,382 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */+package com.datastrato.gravitino.server.web.rest;++import static com.datastrato.gravitino.Configs.TREE_LOCK_CLEAN_INTERVAL;+import static com.datastrato.gravitino.Configs.TREE_LOCK_MAX_NODE_IN_MEMORY;+import static com.datastrato.gravitino.Configs.TREE_LOCK_MIN_NODE_IN_MEMORY;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.Mockito.doThrow;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++import com.datastrato.gravitino.Config;+import com.datastrato.gravitino.GravitinoEnv;+import com.datastrato.gravitino.authorization.AccessControlManager;+import com.datastrato.gravitino.authorization.Group;+import com.datastrato.gravitino.authorization.User;+import com.datastrato.gravitino.dto.requests.RoleGrantRequest;+import com.datastrato.gravitino.dto.requests.RoleRevokeRequest;+import com.datastrato.gravitino.dto.responses.ErrorConstants;+import com.datastrato.gravitino.dto.responses.ErrorResponse;+import com.datastrato.gravitino.dto.responses.GroupResponse;+import com.datastrato.gravitino.dto.responses.UserResponse;+import com.datastrato.gravitino.exceptions.NoSuchMetalakeException;+import com.datastrato.gravitino.exceptions.NoSuchRoleException;+import com.datastrato.gravitino.exceptions.NoSuchUserException;+import com.datastrato.gravitino.lock.LockManager;+import com.datastrato.gravitino.meta.AuditInfo;+import com.datastrato.gravitino.meta.GroupEntity;+import com.datastrato.gravitino.meta.UserEntity;+import com.datastrato.gravitino.rest.RESTUtils;+import com.google.common.collect.Lists;+import java.io.IOException;+import java.time.Instant;+import javax.servlet.http.HttpServletRequest;+import javax.ws.rs.client.Entity;+import javax.ws.rs.core.Application;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;+import org.glassfish.hk2.utilities.binding.AbstractBinder;+import org.glassfish.jersey.server.ResourceConfig;+import org.glassfish.jersey.test.JerseyTest;+import org.glassfish.jersey.test.TestProperties;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;+import org.mockito.Mockito;++public class TestPermissionOperations extends JerseyTest {++ private static final AccessControlManager manager = mock(AccessControlManager.class);++ private static class MockServletRequestFactory extends ServletRequestFactoryBase {+ @Override+ public HttpServletRequest get() {+ HttpServletRequest request = mock(HttpServletRequest.class);+ when(request.getRemoteUser()).thenReturn(null);+ return request;+ }+ }++ @BeforeAll+ public static void setup() {+ Config config = mock(Config.class);+ Mockito.doReturn(100000L).when(config).get(TREE_LOCK_MAX_NODE_IN_MEMORY);+ Mockito.doReturn(1000L).when(config).get(TREE_LOCK_MIN_NODE_IN_MEMORY);+ Mockito.doReturn(36000L).when(config).get(TREE_LOCK_CLEAN_INTERVAL);+ GravitinoEnv.getInstance().setLockManager(new LockManager(config));+ GravitinoEnv.getInstance().setAccessControlManager(manager);+ }++ @Override+ protected Application configure() {+ try {+ forceSet(+ TestProperties.CONTAINER_PORT, String.valueOf(RESTUtils.findAvailablePort(2000, 3000)));+ } catch (IOException e) {+ throw new RuntimeException(e);+ }++ ResourceConfig resourceConfig = new ResourceConfig();+ resourceConfig.register(PermissionOperations.class);+ resourceConfig.register(+ new AbstractBinder() {+ @Override+ protected void configure() {+ bindFactory(MockServletRequestFactory.class).to(HttpServletRequest.class);+ }+ });++ return resourceConfig;+ }++ @Test+ public void testGrantRolesToUser() {+ UserEntity userEntity =+ UserEntity.builder()+ .withId(1L)+ .withName("user")+ .withRoleNames(Lists.newArrayList("roles"))+ .withRoleIds(Lists.newArrayList(1L))+ .withAuditInfo(+ AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build())+ .build();+ when(manager.grantRolesToUser(any(), any(), any())).thenReturn(userEntity);++ RoleGrantRequest request = new RoleGrantRequest(Lists.newArrayList("role1"));++ Response resp =+ target("/metalakes/metalake1/permissions/users/user/grant")+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .put(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));++ Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());+ Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType());++ UserResponse userResponse = resp.readEntity(UserResponse.class);+ Assertions.assertEquals(0, userResponse.getCode());+ User user = userResponse.getUser();+ Assertions.assertEquals(userEntity.roles(), user.roles());+ Assertions.assertEquals(userEntity.name(), user.name());++ // Test to throw NoSuchMetalakeException+ doThrow(new NoSuchMetalakeException("mock error"))+ .when(manager)+ .grantRolesToUser(any(), any(), any());+ Response resp1 =+ target("/metalakes/metalake1/permissions/users/user/grant")+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .put(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));++ Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), resp1.getStatus());+ Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp1.getMediaType());++ ErrorResponse errorResponse = resp1.readEntity(ErrorResponse.class);+ Assertions.assertEquals(ErrorConstants.NOT_FOUND_CODE, errorResponse.getCode());+ Assertions.assertEquals(NoSuchMetalakeException.class.getSimpleName(), errorResponse.getType());++ // Test to throw NoSuchUserException+ doThrow(new NoSuchUserException("mock error"))+ .when(manager)+ .grantRolesToUser(any(), any(), any());+ resp1 =+ target("/metalakes/metalake1/permissions/users/user/grant")+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .put(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));++ Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), resp1.getStatus());+ Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp1.getMediaType());++ errorResponse = resp1.readEntity(ErrorResponse.class);+ Assertions.assertEquals(ErrorConstants.NOT_FOUND_CODE, errorResponse.getCode());+ Assertions.assertEquals(NoSuchUserException.class.getSimpleName(), errorResponse.getType());++ // Test to throw NoSuchRoleException+ doThrow(new NoSuchRoleException("mock error"))+ .when(manager)+ .grantRolesToUser(any(), any(), any());+ resp1 =+ target("/metalakes/metalake1/permissions/users/user/grant")+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .put(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));++ Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), resp1.getStatus());+ Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp1.getMediaType());++ errorResponse = resp1.readEntity(ErrorResponse.class);+ Assertions.assertEquals(ErrorConstants.NOT_FOUND_CODE, errorResponse.getCode());+ Assertions.assertEquals(NoSuchRoleException.class.getSimpleName(), errorResponse.getType());++ // Test to throw internal RuntimeException+ doThrow(new RuntimeException("mock error")).when(manager).grantRolesToUser(any(), any(), any());+ Response resp3 =+ target("/metalakes/metalake1/permissions/users/user/grant")+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .put(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));++ Assertions.assertEquals(+ Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), resp3.getStatus());++ ErrorResponse errorResponse2 = resp3.readEntity(ErrorResponse.class);+ Assertions.assertEquals(ErrorConstants.INTERNAL_ERROR_CODE, errorResponse2.getCode());+ Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResponse2.getType());+ }++ @Test+ public void testGrantRolesToGroup() {+ GroupEntity groupEntity =+ GroupEntity.builder()+ .withId(1L)+ .withName("group")+ .withRoleNames(Lists.newArrayList("roles"))+ .withRoleIds(Lists.newArrayList(1L))+ .withAuditInfo(+ AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build())+ .build();+ when(manager.grantRolesToGroup(any(), any(), any())).thenReturn(groupEntity);++ RoleGrantRequest request = new RoleGrantRequest(Lists.newArrayList("role1"));++ Response resp =+ target("/metalakes/metalake1/permissions/groups/group/grant")+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .put(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));++ Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());+ Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType());++ GroupResponse grantResponse = resp.readEntity(GroupResponse.class);+ Assertions.assertEquals(0, grantResponse.getCode());++ Group group = grantResponse.getGroup();+ Assertions.assertEquals(groupEntity.roles(), group.roles());+ Assertions.assertEquals(groupEntity.name(), group.name());++ // Test to throw NoSuchMetalakeException+ doThrow(new NoSuchMetalakeException("mock error"))+ .when(manager)+ .grantRolesToGroup(any(), any(), any());+ Response resp1 =+ target("/metalakes/metalake1/permissions/groups/group/grant")+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .put(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));++ Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), resp1.getStatus());+ Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp1.getMediaType());++ ErrorResponse errorResponse = resp1.readEntity(ErrorResponse.class);+ Assertions.assertEquals(ErrorConstants.NOT_FOUND_CODE, errorResponse.getCode());+ Assertions.assertEquals(NoSuchMetalakeException.class.getSimpleName(), errorResponse.getType());++ // Test to throw NoSuchUserException+ doThrow(new NoSuchUserException("mock error"))+ .when(manager)+ .grantRolesToGroup(any(), any(), any());+ resp1 =+ target("/metalakes/metalake1/permissions/groups/group/grant")+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .put(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));++ Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), resp1.getStatus());+ Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp1.getMediaType());++ errorResponse = resp1.readEntity(ErrorResponse.class);+ Assertions.assertEquals(ErrorConstants.NOT_FOUND_CODE, errorResponse.getCode());+ Assertions.assertEquals(NoSuchUserException.class.getSimpleName(), errorResponse.getType());++ // Test to throw NoSuchRoleException+ doThrow(new NoSuchRoleException("mock error"))+ .when(manager)+ .grantRolesToGroup(any(), any(), any());+ resp1 =+ target("/metalakes/metalake1/permissions/groups/group/grant")+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .put(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));++ Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), resp1.getStatus());+ Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp1.getMediaType());++ errorResponse = resp1.readEntity(ErrorResponse.class);+ Assertions.assertEquals(ErrorConstants.NOT_FOUND_CODE, errorResponse.getCode());+ Assertions.assertEquals(NoSuchRoleException.class.getSimpleName(), errorResponse.getType());++ // Test to throw internal RuntimeException+ doThrow(new RuntimeException("mock error"))+ .when(manager)+ .grantRolesToGroup(any(), any(), any());+ Response resp3 =+ target("/metalakes/metalake1/permissions/groups/group/grant")+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .put(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));++ Assertions.assertEquals(+ Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), resp3.getStatus());++ ErrorResponse errorResponse2 = resp3.readEntity(ErrorResponse.class);+ Assertions.assertEquals(ErrorConstants.INTERNAL_ERROR_CODE, errorResponse2.getCode());+ Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResponse2.getType());+ }++ @Test+ public void testRevokeRolesFromUser() {+ UserEntity userEntity =+ UserEntity.builder()+ .withId(1L)+ .withName("user")+ .withRoleNames(Lists.newArrayList())+ .withRoleIds(Lists.newArrayList(1L))+ .withAuditInfo(+ AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build())+ .build();+ when(manager.revokeRolesFromUser(any(), any(), any())).thenReturn(userEntity);+ RoleRevokeRequest request = new RoleRevokeRequest(Lists.newArrayList("role1"));++ Response resp =+ target("/metalakes/metalake1/permissions/users/user1/revoke")+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .put(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));++ Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());+ UserResponse revokeResponse = resp.readEntity(UserResponse.class);+ Assertions.assertEquals(0, revokeResponse.getCode());++ User user = revokeResponse.getUser();+ Assertions.assertEquals(userEntity.roles(), user.roles());+ Assertions.assertEquals(userEntity.name(), user.name());++ doThrow(new RuntimeException("mock error"))+ .when(manager)+ .revokeRolesFromUser(any(), any(), any());+ Response resp3 =+ target("/metalakes/metalake1/permissions/users/user1/revoke")+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .put(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));++ Assertions.assertEquals(+ Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), resp3.getStatus());++ ErrorResponse errorResponse = resp3.readEntity(ErrorResponse.class);+ Assertions.assertEquals(ErrorConstants.INTERNAL_ERROR_CODE, errorResponse.getCode());+ Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResponse.getType());+ }++ @Test+ public void testRevokeRolesFromGroup() {+ GroupEntity groupEntity =+ GroupEntity.builder()+ .withId(1L)+ .withName("group")+ .withRoleNames(Lists.newArrayList())+ .withRoleIds(Lists.newArrayList(1L))+ .withAuditInfo(+ AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build())+ .build();+ when(manager.revokeRolesFromGroup(any(), any(), any())).thenReturn(groupEntity);+ RoleRevokeRequest request = new RoleRevokeRequest(Lists.newArrayList("role1"));++ Response resp =+ target("/metalakes/metalake1/permissions/groups/group1/revoke")+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .put(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));++ Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());+ GroupResponse revokeResponse = resp.readEntity(GroupResponse.class);+ Assertions.assertEquals(0, revokeResponse.getCode());++ Group group = revokeResponse.getGroup();+ Assertions.assertEquals(groupEntity.roles(), group.roles());+ Assertions.assertEquals(groupEntity.name(), group.name());++ doThrow(new RuntimeException("mock error"))+ .when(manager)+ .revokeRolesFromGroup(any(), any(), any());+ Response resp3 =+ target("/metalakes/metalake1/permissions/groups/group1/revoke")+ .request(MediaType.APPLICATION_JSON_TYPE)+ .accept("application/vnd.gravitino.v1+json")+ .put(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));++ Assertions.assertEquals(+ Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), resp3.getStatus());++ ErrorResponse errorResponse = resp3.readEntity(ErrorResponse.class);+ Assertions.assertEquals(ErrorConstants.INTERNAL_ERROR_CODE, errorResponse.getCode());+ Assertions.assertEquals(RuntimeException.class.getSimpleName(), errorResponse.getType());+ }+}