Skip to content

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

[#2239] feat(server): Add the role operation (#2956)

qqqttt12386e7f46768b6
diff --git a/api/src/main/java/com/datastrato/gravitino/authorization/SecurableObjects.java b/api/src/main/java/com/datastrato/gravitino/authorization/SecurableObjects.java
index 48b05f6ef6..80d68836b8 100644
--- a/api/src/main/java/com/datastrato/gravitino/authorization/SecurableObjects.java
+++ b/api/src/main/java/com/datastrato/gravitino/authorization/SecurableObjects.java
@@ -4,11 +4,16 @@
*/
package com.datastrato.gravitino.authorization;
+import com.google.common.base.Splitter;
+import com.google.common.collect.Iterables;
import java.util.Objects;
+import org.apache.commons.lang3.StringUtils;
/** The helper class for {@link SecurableObject}. */
public class SecurableObjects {
+ private static final Splitter DOT = Splitter.on('.');
+
/**
* Create the {@link SecurableObject} with the given names.
*
@@ -186,4 +191,23 @@ public class SecurableObjects {
&& Objects.equals(name, otherSecurableObject.name());
}
}
+
+ /**
+ * Create a {@link SecurableObject} from the given identifier string.
+ *
+ * @param securableObjectIdentifier The identifier string
+ * @return The created {@link SecurableObject}
+ */
+ public static SecurableObject parse(String securableObjectIdentifier) {
+ if ("*".equals(securableObjectIdentifier)) {
+ return SecurableObjects.ofAllCatalogs();
+ }
+
+ if (StringUtils.isBlank(securableObjectIdentifier)) {
+ throw new IllegalArgumentException("securable object identifier can't be blank");
+ }
+
+ Iterable<String> parts = DOT.split(securableObjectIdentifier);
+ return SecurableObjects.of(Iterables.toArray(parts, String.class));
+ }
}
diff --git a/common/src/main/java/com/datastrato/gravitino/dto/authorization/RoleDTO.java b/common/src/main/java/com/datastrato/gravitino/dto/authorization/RoleDTO.java
new file mode 100644
index 0000000000..2f50da3a35
--- /dev/null
+++ b/common/src/main/java/com/datastrato/gravitino/dto/authorization/RoleDTO.java
@@ -0,0 +1,231 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.dto.authorization;
+
+import com.datastrato.gravitino.Audit;
+import com.datastrato.gravitino.authorization.Privilege;
+import com.datastrato.gravitino.authorization.Privileges;
+import com.datastrato.gravitino.authorization.Role;
+import com.datastrato.gravitino.authorization.SecurableObject;
+import com.datastrato.gravitino.authorization.SecurableObjects;
+import com.datastrato.gravitino.dto.AuditDTO;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.base.Preconditions;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.stream.Collectors;
+import javax.annotation.Nullable;
+import org.apache.commons.collections4.CollectionUtils;
+import org.apache.commons.lang3.StringUtils;
+
+/** Represents a Role Data Transfer Object (DTO). */
+public class RoleDTO implements Role {
+
+ @JsonProperty("name")
+ private String name;
+
+ @JsonProperty("audit")
+ private AuditDTO audit;
+
+ @Nullable
+ @JsonProperty("properties")
+ private Map<String, String> properties;
+
+ @JsonProperty("privileges")
+ private List<String> privileges;
+
+ @JsonProperty("securableObject")
+ private String securableObject;
+
+ /** Default constructor for Jackson deserialization. */
+ protected RoleDTO() {}
+
+ /**
+ * Creates a new instance of RoleDTO.
+ *
+ * @param name The name of the Role DTO.
+ * @param properties The properties of the Role DTO.
+ * @param privileges The privileges of the Role DTO.
+ * @param securableObject The securable object of the Role DTO.
+ * @param audit The audit information of the Role DTO.
+ */
+ protected RoleDTO(
+ String name,
+ Map<String, String> properties,
+ List<String> privileges,
+ String securableObject,
+ AuditDTO audit) {
+ this.name = name;
+ this.audit = audit;
+ this.properties = properties;
+ this.privileges = privileges;
+ this.securableObject = securableObject;
+ }
+
+ /** @return The name of the Role DTO. */
+ @Override
+ public String name() {
+ return name;
+ }
+
+ /**
+ * The properties of the role. Note, this method will return null if the properties are not set.
+ *
+ * @return The properties of the role.
+ */
+ @Override
+ public Map<String, String> properties() {
+ return properties;
+ }
+
+ /**
+ * The privileges of the role. All privileges belong to one resource. For example: If the resource
+ * is a table, the privileges could be `READ TABLE`, `WRITE TABLE`, etc. If a schema has the
+ * privilege of `LOAD TABLE`. It means the role can all tables of the schema.
+ *
+ * @return The privileges of the role.
+ */
+ @Override
+ public List<Privilege> privileges() {
+ return privileges.stream().map(Privileges::fromString).collect(Collectors.toList());
+ }
+
+ /**
+ * The resource represents a special kind of entity with a unique identifier. All resources are
+ * organized by tree structure. For example: If the resource is a table, the identifier may be
+ * `catalog1.schema1.table1`.
+ *
+ * @return The securable object of the role.
+ */
+ @Override
+ public SecurableObject securableObject() {
+ return SecurableObjects.parse(securableObject);
+ }
+
+ /** @return The audit information of the Role DTO. */
+ @Override
+ public Audit auditInfo() {
+ return audit;
+ }
+
+ /**
+ * Creates a new Builder for constructing a Role DTO.
+ *
+ * @return A new Builder instance.
+ */
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ /**
+ * Builder class for constructing a RoleDTO instance.
+ *
+ * @param <S> The type of the builder instance.
+ */
+ public static class Builder<S extends Builder> {
+
+ /** The name of the role. */
+ protected String name;
+
+ /** The privileges of the role. */
+ protected List<Privilege> privileges = Collections.emptyList();
+
+ /** The audit information of the role. */
+ protected AuditDTO audit;
+
+ /** The properties of the role. */
+ protected Map<String, String> properties;
+
+ /** The securable object of the role. */
+ protected SecurableObject securableObject;
+
+ /**
+ * Sets the name of the role.
+ *
+ * @param name The name of the role.
+ * @return The builder instance.
+ */
+ public S withName(String name) {
+ this.name = name;
+ return (S) this;
+ }
+
+ /**
+ * Sets the privileges of the role.
+ *
+ * @param privileges The privileges of the role.
+ * @return The builder instance.
+ */
+ public S withPrivileges(List<Privilege> privileges) {
+ if (privileges != null) {
+ this.privileges = privileges;
+ }
+
+ return (S) this;
+ }
+
+ /**
+ * Sets the properties of the role.
+ *
+ * @param properties The properties of the role.
+ * @return The builder instance.
+ */
+ public S withProperties(Map<String, String> properties) {
+ if (properties != null) {
+ this.properties = properties;
+ }
+
+ return (S) this;
+ }
+
+ /**
+ * Sets the securable object of the role.
+ *
+ * @param securableObject The securableObject of the role.
+ * @return The builder instance.
+ */
+ public S withSecurableObject(SecurableObject securableObject) {
+ this.securableObject = securableObject;
+ return (S) this;
+ }
+
+ /**
+ * Sets the audit information of the role.
+ *
+ * @param audit The audit information of the role.
+ * @return The builder instance.
+ */
+ public S withAudit(AuditDTO audit) {
+ this.audit = audit;
+ return (S) this;
+ }
+
+ /**
+ * Builds an instance of RoleDTO using the builder's properties.
+ *
+ * @return An instance of RoleDTO.
+ * @throws IllegalArgumentException If the name or audit are not set.
+ */
+ public RoleDTO build() {
+ Preconditions.checkArgument(StringUtils.isNotBlank(name), "name cannot be null or empty");
+ Preconditions.checkArgument(audit != null, "audit cannot be null");
+ Preconditions.checkArgument(
+ !CollectionUtils.isEmpty(privileges), "privileges can't be empty");
+ Preconditions.checkArgument(securableObject != null, "securable object can't null");
+
+ return new RoleDTO(
+ name,
+ properties,
+ privileges.stream()
+ .map(Privilege::name)
+ .map(Objects::toString)
+ .collect(Collectors.toList()),
+ securableObject.toString(),
+ audit);
+ }
+ }
+}
diff --git a/common/src/main/java/com/datastrato/gravitino/dto/requests/RoleCreateRequest.java b/common/src/main/java/com/datastrato/gravitino/dto/requests/RoleCreateRequest.java
new file mode 100644
index 0000000000..f2deaf72f9
--- /dev/null
+++ b/common/src/main/java/com/datastrato/gravitino/dto/requests/RoleCreateRequest.java
@@ -0,0 +1,82 @@
+/*
+ * 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 java.util.Map;
+import javax.annotation.Nullable;
+import lombok.Builder;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.ToString;
+import lombok.extern.jackson.Jacksonized;
+import org.apache.commons.collections4.CollectionUtils;
+import org.apache.commons.lang3.StringUtils;
+
+/** Represents a request to create a role. */
+@Getter
+@EqualsAndHashCode
+@ToString
+@Builder
+@Jacksonized
+public class RoleCreateRequest implements RESTRequest {
+
+ @JsonProperty("name")
+ private final String name;
+
+ @Nullable
+ @JsonProperty("properties")
+ private Map<String, String> properties;
+
+ @JsonProperty("privileges")
+ private List<String> privileges;
+
+ @JsonProperty("securableObject")
+ private String securableObject;
+
+ /** Default constructor for RoleCreateRequest. (Used for Jackson deserialization.) */
+ public RoleCreateRequest() {
+ this(null, null, null, null);
+ }
+
+ /**
+ * Creates a new RoleCreateRequest.
+ *
+ * @param name 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.
+ */
+ public RoleCreateRequest(
+ String name,
+ Map<String, String> properties,
+ List<String> privileges,
+ String securableObject) {
+ super();
+ this.name = name;
+ this.properties = properties;
+ this.privileges = privileges;
+ this.securableObject = securableObject;
+ }
+
+ /**
+ * Validates the {@link RoleCreateRequest} request.
+ *
+ * @throws IllegalArgumentException If the request is invalid, this exception is thrown.
+ */
+ @Override
+ public void validate() throws IllegalArgumentException {
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(name), "\"name\" field is required and cannot be empty");
+
+ Preconditions.checkArgument(
+ !CollectionUtils.isEmpty(privileges), "\"privileges\" can't be empty");
+
+ Preconditions.checkArgument(securableObject != null, "\"securableObject\" can't null");
+ }
+}
diff --git a/common/src/main/java/com/datastrato/gravitino/dto/responses/RoleResponse.java b/common/src/main/java/com/datastrato/gravitino/dto/responses/RoleResponse.java
new file mode 100644
index 0000000000..5c1086bb43
--- /dev/null
+++ b/common/src/main/java/com/datastrato/gravitino/dto/responses/RoleResponse.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.dto.responses;
+
+import com.datastrato.gravitino.dto.authorization.RoleDTO;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.base.Preconditions;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.ToString;
+import org.apache.commons.collections4.CollectionUtils;
+import org.apache.commons.lang3.StringUtils;
+
+/** Represents a response for a role. */
+@Getter
+@ToString
+@EqualsAndHashCode(callSuper = true)
+public class RoleResponse extends BaseResponse {
+
+ @JsonProperty("role")
+ private final RoleDTO role;
+
+ /**
+ * Constructor for RoleResponse.
+ *
+ * @param role The role data transfer object.
+ */
+ public RoleResponse(RoleDTO role) {
+ super(0);
+ this.role = role;
+ }
+
+ /** Default constructor for RoleResponse. (Used for Jackson deserialization.) */
+ public RoleResponse() {
+ super();
+ this.role = null;
+ }
+
+ /**
+ * Validates the response data.
+ *
+ * @throws IllegalArgumentException if the name or audit is not set.
+ */
+ @Override
+ public void validate() throws IllegalArgumentException {
+ super.validate();
+
+ Preconditions.checkArgument(role != null, "role must not be null");
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(role.name()), "role 'name' must not be null and empty");
+ Preconditions.checkArgument(role.auditInfo() != null, "role 'auditInfo' must not be null");
+ Preconditions.checkArgument(
+ !CollectionUtils.isEmpty(role.privileges()), "role 'privileges' can't be empty");
+ Preconditions.checkArgument(
+ role.securableObject() != null, "role 'securableObject' can't null");
+ }
+}
diff --git a/common/src/main/java/com/datastrato/gravitino/dto/util/DTOConverters.java b/common/src/main/java/com/datastrato/gravitino/dto/util/DTOConverters.java
index a2050e5354..ad93bfbf56 100644
--- a/common/src/main/java/com/datastrato/gravitino/dto/util/DTOConverters.java
+++ b/common/src/main/java/com/datastrato/gravitino/dto/util/DTOConverters.java
@@ -10,11 +10,13 @@ import com.datastrato.gravitino.Audit;
import com.datastrato.gravitino.Catalog;
import com.datastrato.gravitino.Metalake;
import com.datastrato.gravitino.authorization.Group;
+import com.datastrato.gravitino.authorization.Role;
import com.datastrato.gravitino.authorization.User;
import com.datastrato.gravitino.dto.AuditDTO;
import com.datastrato.gravitino.dto.CatalogDTO;
import com.datastrato.gravitino.dto.MetalakeDTO;
import com.datastrato.gravitino.dto.authorization.GroupDTO;
+import com.datastrato.gravitino.dto.authorization.RoleDTO;
import com.datastrato.gravitino.dto.authorization.UserDTO;
import com.datastrato.gravitino.dto.file.FilesetDTO;
import com.datastrato.gravitino.dto.messaging.TopicDTO;
@@ -369,6 +371,26 @@ public class DTOConverters {
.build();
}
+ /**
+ * Converts a role implementation to a RoleDTO.
+ *
+ * @param role The role implementation.
+ * @return The role DTO.
+ */
+ public static RoleDTO toDTO(Role role) {
+ if (role instanceof RoleDTO) {
+ return (RoleDTO) role;
+ }
+
+ return RoleDTO.builder()
+ .withName(role.name())
+ .withSecurableObject(role.securableObject())
+ .withPrivileges(role.privileges())
+ .withProperties(role.properties())
+ .withAudit(toDTO(role.auditInfo()))
+ .build();
+ }
+
/**
* Converts a Expression to an FunctionArg DTO.
*
diff --git a/common/src/test/java/com/datastrato/gravitino/dto/responses/TestResponses.java b/common/src/test/java/com/datastrato/gravitino/dto/responses/TestResponses.java
index 4465cc34f1..96b27b0e85 100644
--- a/common/src/test/java/com/datastrato/gravitino/dto/responses/TestResponses.java
+++ b/common/src/test/java/com/datastrato/gravitino/dto/responses/TestResponses.java
@@ -11,16 +11,20 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import com.datastrato.gravitino.Catalog;
import com.datastrato.gravitino.NameIdentifier;
+import com.datastrato.gravitino.authorization.Privileges;
+import com.datastrato.gravitino.authorization.SecurableObjects;
import com.datastrato.gravitino.dto.AuditDTO;
import com.datastrato.gravitino.dto.CatalogDTO;
import com.datastrato.gravitino.dto.MetalakeDTO;
import com.datastrato.gravitino.dto.authorization.GroupDTO;
+import com.datastrato.gravitino.dto.authorization.RoleDTO;
import com.datastrato.gravitino.dto.authorization.UserDTO;
import com.datastrato.gravitino.dto.rel.ColumnDTO;
import com.datastrato.gravitino.dto.rel.SchemaDTO;
import com.datastrato.gravitino.dto.rel.TableDTO;
import com.datastrato.gravitino.dto.rel.partitioning.Partitioning;
import com.datastrato.gravitino.rel.types.Types;
+import com.google.common.collect.Lists;
import java.time.Instant;
import org.junit.jupiter.api.Test;
@@ -241,6 +245,7 @@ public class TestResponses {
assertThrows(IllegalArgumentException.class, () -> user.validate());
}
+ @Test
void testGroupResponse() throws IllegalArgumentException {
AuditDTO audit =
AuditDTO.builder().withCreator("creator").withCreateTime(Instant.now()).build();
@@ -254,4 +259,25 @@ public class TestResponses {
GroupResponse group = new GroupResponse();
assertThrows(IllegalArgumentException.class, () -> group.validate());
}
+
+ @Test
+ void testRoleResponse() throws IllegalArgumentException {
+ AuditDTO audit =
+ AuditDTO.builder().withCreator("creator").withCreateTime(Instant.now()).build();
+ RoleDTO role =
+ RoleDTO.builder()
+ .withName("role1")
+ .withPrivileges(Lists.newArrayList(Privileges.LoadCatalog.get()))
+ .withSecurableObject(SecurableObjects.ofCatalog("catalog"))
+ .withAudit(audit)
+ .build();
+ RoleResponse response = new RoleResponse(role);
+ response.validate(); // No exception thrown
+ }
+
+ @Test
+ void testRoleResponseException() throws IllegalArgumentException {
+ RoleResponse role = new RoleResponse();
+ assertThrows(IllegalArgumentException.class, () -> role.validate());
+ }
}
diff --git a/core/src/main/java/com/datastrato/gravitino/authorization/RoleManager.java b/core/src/main/java/com/datastrato/gravitino/authorization/RoleManager.java
index 5813744af1..35639e4726 100644
--- a/core/src/main/java/com/datastrato/gravitino/authorization/RoleManager.java
+++ b/core/src/main/java/com/datastrato/gravitino/authorization/RoleManager.java
@@ -66,7 +66,7 @@ class RoleManager {
.withId(idGenerator.nextId())
.withName(role)
.withProperties(properties)
- .securableObject(securableObject)
+ .withSecurableObject(securableObject)
.withPrivileges(privileges)
.withNamespace(
Namespace.of(
diff --git a/core/src/main/java/com/datastrato/gravitino/meta/RoleEntity.java b/core/src/main/java/com/datastrato/gravitino/meta/RoleEntity.java
index 5e4948fa0b..b4642f3e5d 100644
--- a/core/src/main/java/com/datastrato/gravitino/meta/RoleEntity.java
+++ b/core/src/main/java/com/datastrato/gravitino/meta/RoleEntity.java
@@ -234,7 +234,7 @@ public class RoleEntity implements Role, Entity, Auditable, HasIdentifier {
* @param securableObject The securable object of the role entity.
* @return The builder instance.
*/
- public Builder securableObject(SecurableObject securableObject) {
+ public Builder withSecurableObject(SecurableObject securableObject) {
roleEntity.securableObject = securableObject;
return this;
}
diff --git a/core/src/main/java/com/datastrato/gravitino/proto/RoleEntitySerDe.java b/core/src/main/java/com/datastrato/gravitino/proto/RoleEntitySerDe.java
index ae65c3a117..e4a96ae7e6 100644
--- a/core/src/main/java/com/datastrato/gravitino/proto/RoleEntitySerDe.java
+++ b/core/src/main/java/com/datastrato/gravitino/proto/RoleEntitySerDe.java
@@ -5,18 +5,12 @@
package com.datastrato.gravitino.proto;
import com.datastrato.gravitino.authorization.Privileges;
-import com.datastrato.gravitino.authorization.SecurableObject;
import com.datastrato.gravitino.authorization.SecurableObjects;
import com.datastrato.gravitino.meta.RoleEntity;
-import com.google.common.base.Splitter;
-import com.google.common.collect.Iterables;
import java.util.stream.Collectors;
-import org.apache.commons.lang3.StringUtils;
public class RoleEntitySerDe implements ProtoSerDe<RoleEntity, Role> {
- private static final Splitter DOT = Splitter.on('.');
-
/**
* Serializes the provided entity into its corresponding Protocol Buffer message representation.
*
@@ -59,7 +53,7 @@ public class RoleEntitySerDe implements ProtoSerDe<RoleEntity, Role> {
role.getPrivilegesList().stream()
.map(Privileges::fromString)
.collect(Collectors.toList()))
- .securableObject(parseSecurableObject(role.getSecurableObject()))
+ .withSecurableObject(SecurableObjects.parse(role.getSecurableObject()))
.withAuditInfo(new AuditInfoSerDe().deserialize(role.getAuditInfo()));
if (!role.getPropertiesMap().isEmpty()) {
@@ -68,17 +62,4 @@ public class RoleEntitySerDe implements ProtoSerDe<RoleEntity, Role> {
return builder.build();
}
-
- private static SecurableObject parseSecurableObject(String securableObjectIdentifier) {
- if ("*".equals(securableObjectIdentifier)) {
- return SecurableObjects.ofAllCatalogs();
- }
-
- if (StringUtils.isBlank(securableObjectIdentifier)) {
- throw new IllegalArgumentException("securable object identifier can't be blank");
- }
-
- Iterable<String> parts = DOT.split(securableObjectIdentifier);
- return SecurableObjects.of(Iterables.toArray(parts, String.class));
- }
}
diff --git a/core/src/test/java/com/datastrato/gravitino/meta/TestEntity.java b/core/src/test/java/com/datastrato/gravitino/meta/TestEntity.java
index 5d1f689a6a..b852d34010 100644
--- a/core/src/test/java/com/datastrato/gravitino/meta/TestEntity.java
+++ b/core/src/test/java/com/datastrato/gravitino/meta/TestEntity.java
@@ -266,7 +266,7 @@ public class TestEntity {
.withId(1L)
.withName(roleName)
.withAuditInfo(auditInfo)
- .securableObject(SecurableObjects.of(catalogName))
+ .withSecurableObject(SecurableObjects.of(catalogName))
.withPrivileges(Lists.newArrayList(Privileges.LoadCatalog.get()))
.withProperties(map)
.build();
@@ -286,7 +286,7 @@ public class TestEntity {
.withId(1L)
.withName(roleName)
.withAuditInfo(auditInfo)
- .securableObject(SecurableObjects.of(catalogName))
+ .withSecurableObject(SecurableObjects.of(catalogName))
.withPrivileges(Lists.newArrayList(Privileges.LoadCatalog.get()))
.build();
Assertions.assertNull(roleWithoutFields.properties());
diff --git a/core/src/test/java/com/datastrato/gravitino/proto/TestEntityProtoSerDe.java b/core/src/test/java/com/datastrato/gravitino/proto/TestEntityProtoSerDe.java
index 9b63d32167..8223ac239c 100644
--- a/core/src/test/java/com/datastrato/gravitino/proto/TestEntityProtoSerDe.java
+++ b/core/src/test/java/com/datastrato/gravitino/proto/TestEntityProtoSerDe.java
@@ -332,7 +332,7 @@ public class TestEntityProtoSerDe {
.withId(roleId)
.withName(roleName)
.withAuditInfo(auditInfo)
- .securableObject(SecurableObjects.of(catalogName))
+ .withSecurableObject(SecurableObjects.of(catalogName))
.withPrivileges(Lists.newArrayList(Privileges.LoadCatalog.get()))
.withProperties(props)
.build();
@@ -345,7 +345,7 @@ public class TestEntityProtoSerDe {
.withId(1L)
.withName(roleName)
.withAuditInfo(auditInfo)
- .securableObject(SecurableObjects.of(catalogName))
+ .withSecurableObject(SecurableObjects.of(catalogName))
.withPrivileges(Lists.newArrayList(Privileges.LoadCatalog.get()))
.build();
roleBytes = protoEntitySerDe.serialize(roleWithoutFields);
diff --git a/core/src/test/java/com/datastrato/gravitino/storage/TestEntityStorage.java b/core/src/test/java/com/datastrato/gravitino/storage/TestEntityStorage.java
index b7272c413a..4df9a63f7d 100644
--- a/core/src/test/java/com/datastrato/gravitino/storage/TestEntityStorage.java
+++ b/core/src/test/java/com/datastrato/gravitino/storage/TestEntityStorage.java
@@ -1182,7 +1182,7 @@ public class TestEntityStorage {
metalake, CatalogEntity.SYSTEM_CATALOG_RESERVED_NAME, Entity.ROLE_SCHEMA_NAME))
.withName(name)
.withAuditInfo(auditInfo)
- .securableObject(SecurableObjects.of("catalog"))
+ .withSecurableObject(SecurableObjects.of("catalog"))
.withPrivileges(Lists.newArrayList(Privileges.LoadCatalog.get()))
.withProperties(Collections.emptyMap())
.build();
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.java
index 0921a8690f..130c6f2fa8 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
@@ -12,6 +12,7 @@ import com.datastrato.gravitino.exceptions.NoSuchMetalakeException;
import com.datastrato.gravitino.exceptions.NonEmptySchemaException;
import com.datastrato.gravitino.exceptions.NotFoundException;
import com.datastrato.gravitino.exceptions.PartitionAlreadyExistsException;
+import com.datastrato.gravitino.exceptions.RoleAlreadyExistsException;
import com.datastrato.gravitino.exceptions.SchemaAlreadyExistsException;
import com.datastrato.gravitino.exceptions.TableAlreadyExistsException;
import com.datastrato.gravitino.exceptions.TopicAlreadyExistsException;
@@ -68,6 +69,11 @@ public class ExceptionHandlers {
return GroupExceptionHandler.INSTANCE.handle(op, group, metalake, e);
}
+ public static Response handleRoleException(
+ OperationType op, String role, String metalake, Exception e) {
+ return RoleExceptionHandler.INSTANCE.handle(op, role, metalake, e);
+ }
+
public static Response handleTopicException(
OperationType op, String topic, String schema, Exception e) {
return TopicExceptionHandler.INSTANCE.handle(op, topic, schema, e);
@@ -345,6 +351,38 @@ public class ExceptionHandlers {
}
}
+ private static class RoleExceptionHandler extends BaseExceptionHandler {
+
+ private static final ExceptionHandler INSTANCE = new RoleExceptionHandler();
+
+ private static String getRoleErrorMsg(
+ String role, String operation, String metalake, String reason) {
+ return String.format(
+ "Failed to operate role %s operation [%s] under metalake [%s], reason [%s]",
+ role, operation, metalake, reason);
+ }
+
+ @Override
+ public Response handle(OperationType op, String role, String metalake, Exception e) {
+ String formatted = StringUtil.isBlank(role) ? "" : " [" + role + "]";
+ String errorMsg = getRoleErrorMsg(formatted, op.name(), metalake, 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 if (e instanceof RoleAlreadyExistsException) {
+ return Utils.alreadyExists(errorMsg, e);
+
+ } else {
+ return super.handle(op, role, metalake, e);
+ }
+ }
+ }
+
private static class TopicExceptionHandler extends BaseExceptionHandler {
private static final ExceptionHandler INSTANCE = new TopicExceptionHandler();
diff --git a/server/src/main/java/com/datastrato/gravitino/server/web/rest/RoleOperations.java b/server/src/main/java/com/datastrato/gravitino/server/web/rest/RoleOperations.java
new file mode 100644
index 0000000000..c89f27d0a7
--- /dev/null
+++ b/server/src/main/java/com/datastrato/gravitino/server/web/rest/RoleOperations.java
@@ -0,0 +1,108 @@
+/*
+ * 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.authorization.Privileges;
+import com.datastrato.gravitino.authorization.SecurableObjects;
+import com.datastrato.gravitino.dto.requests.RoleCreateRequest;
+import com.datastrato.gravitino.dto.responses.DropResponse;
+import com.datastrato.gravitino.dto.responses.RoleResponse;
+import com.datastrato.gravitino.dto.util.DTOConverters;
+import com.datastrato.gravitino.metrics.MetricNames;
+import com.datastrato.gravitino.server.web.Utils;
+import java.util.stream.Collectors;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+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.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Path("/metalakes/{metalake}/roles")
+public class RoleOperations {
+ private static final Logger LOG = LoggerFactory.getLogger(RoleOperations.class);
+
+ private final AccessControlManager accessControlManager;
+
+ @Context private HttpServletRequest httpRequest;
+
+ public RoleOperations() {
+ this.accessControlManager = GravitinoEnv.getInstance().accessControlManager();
+ }
+
+ @GET
+ @Path("{role}")
+ @Produces("application/vnd.gravitino.v1+json")
+ @Timed(name = "load-role." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "load-role", absolute = true)
+ public Response loadRole(@PathParam("metalake") String metalake, @PathParam("role") String role) {
+ try {
+ return Utils.doAs(
+ httpRequest,
+ () ->
+ Utils.ok(
+ new RoleResponse(
+ DTOConverters.toDTO(accessControlManager.loadRole(metalake, role)))));
+ } catch (Exception e) {
+ return ExceptionHandlers.handleRoleException(OperationType.LOAD, role, metalake, e);
+ }
+ }
+
+ @POST
+ @Produces("application/vnd.gravitino.v1+json")
+ @Timed(name = "create-role." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "create-role", absolute = true)
+ public Response creatRole(@PathParam("metalake") String metalake, RoleCreateRequest request) {
+ try {
+ return Utils.doAs(
+ httpRequest,
+ () ->
+ Utils.ok(
+ new RoleResponse(
+ DTOConverters.toDTO(
+ accessControlManager.createRole(
+ metalake,
+ request.getName(),
+ request.getProperties(),
+ SecurableObjects.parse(request.getSecurableObject()),
+ request.getPrivileges().stream()
+ .map(Privileges::fromString)
+ .collect(Collectors.toList()))))));
+ } catch (Exception e) {
+ return ExceptionHandlers.handleRoleException(
+ OperationType.CREATE, request.getName(), metalake, e);
+ }
+ }
+
+ @DELETE
+ @Path("{role}")
+ @Produces("application/vnd.gravitino.v1+json")
+ @Timed(name = "drop-role." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+ @ResponseMetered(name = "drop-role", absolute = true)
+ public Response dropRole(@PathParam("metalake") String metalake, @PathParam("role") String role) {
+ try {
+ return Utils.doAs(
+ httpRequest,
+ () -> {
+ boolean dropped = accessControlManager.dropRole(metalake, role);
+ if (!dropped) {
+ LOG.warn("Failed to drop role {} under metalake {}", role, metalake);
+ }
+ return Utils.ok(new DropResponse(dropped));
+ });
+ } catch (Exception e) {
+ return ExceptionHandlers.handleRoleException(OperationType.DROP, role, metalake, e);
+ }
+ }
+}
diff --git a/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestRoleOperations.java b/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestRoleOperations.java
new file mode 100644
index 0000000000..17d74cc02b
--- /dev/null
+++ b/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestRoleOperations.java
@@ -0,0 +1,298 @@
+/*
+ * 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.Privileges;
+import com.datastrato.gravitino.authorization.Role;
+import com.datastrato.gravitino.authorization.SecurableObjects;
+import com.datastrato.gravitino.dto.authorization.RoleDTO;
+import com.datastrato.gravitino.dto.requests.RoleCreateRequest;
+import com.datastrato.gravitino.dto.responses.DropResponse;
+import com.datastrato.gravitino.dto.responses.ErrorConstants;
+import com.datastrato.gravitino.dto.responses.ErrorResponse;
+import com.datastrato.gravitino.dto.responses.RoleResponse;
+import com.datastrato.gravitino.exceptions.NoSuchMetalakeException;
+import com.datastrato.gravitino.exceptions.NoSuchRoleException;
+import com.datastrato.gravitino.exceptions.RoleAlreadyExistsException;
+import com.datastrato.gravitino.lock.LockManager;
+import com.datastrato.gravitino.meta.AuditInfo;
+import com.datastrato.gravitino.meta.RoleEntity;
+import com.datastrato.gravitino.rest.RESTUtils;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+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 TestRoleOperations 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(RoleOperations.class);
+ resourceConfig.register(
+ new AbstractBinder() {
+ @Override
+ protected void configure() {
+ bindFactory(MockServletRequestFactory.class).to(HttpServletRequest.class);
+ }
+ });
+
+ return resourceConfig;
+ }
+
+ @Test
+ public void testCreateRole() {
+ RoleCreateRequest req =
+ new RoleCreateRequest(
+ "role",
+ Collections.emptyMap(),
+ Lists.newArrayList(Privileges.LoadCatalog.get().name().toString()),
+ SecurableObjects.of("catalog").toString());
+ Role role = buildRole("role1");
+
+ when(manager.createRole(any(), any(), any(), any(), any())).thenReturn(role);
+
+ Response resp =
+ target("/metalakes/metalake1/roles")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .post(Entity.entity(req, MediaType.APPLICATION_JSON_TYPE));
+
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());
+ Assertions.assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType());
+
+ RoleResponse roleResponse = resp.readEntity(RoleResponse.class);
+ Assertions.assertEquals(0, roleResponse.getCode());
+
+ RoleDTO roleDTO = roleResponse.getRole();
+ Assertions.assertEquals("role1", roleDTO.name());
+ Assertions.assertEquals(SecurableObjects.of("catalog"), roleDTO.securableObject());
+ Assertions.assertEquals(Lists.newArrayList(Privileges.LoadCatalog.get()), roleDTO.privileges());
+
+ // Test to throw NoSuchMetalakeException
+ doThrow(new NoSuchMetalakeException("mock error"))
+ .when(manager)
+ .createRole(any(), any(), any(), any(), any());
+ Response resp1 =
+ target("/metalakes/metalake1/roles")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .post(Entity.entity(req, 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 RoleAlreadyExistsException
+ doThrow(new RoleAlreadyExistsException("mock error"))
+ .when(manager)
+ .createRole(any(), any(), any(), any(), any());
+ Response resp2 =
+ target("/metalakes/metalake1/roles")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .post(Entity.entity(req, MediaType.APPLICATION_JSON_TYPE));
+
+ Assertions.assertEquals(Response.Status.CONFLICT.getStatusCode(), resp2.getStatus());
+
+ ErrorResponse errorResponse1 = resp2.readEntity(ErrorResponse.class);
+ Assertions.assertEquals(ErrorConstants.ALREADY_EXISTS_CODE, errorResponse1.getCode());
+ Assertions.assertEquals(
+ RoleAlreadyExistsException.class.getSimpleName(), errorResponse1.getType());
+
+ // Test to throw internal RuntimeException
+ doThrow(new RuntimeException("mock error"))
+ .when(manager)
+ .createRole(any(), any(), any(), any(), any());
+ Response resp3 =
+ target("/metalakes/metalake1/roles")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .post(Entity.entity(req, 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 testLoadRole() {
+ Role role = buildRole("role1");
+
+ when(manager.loadRole(any(), any())).thenReturn(role);
+
+ Response resp =
+ target("/metalakes/metalake1/roles/role1")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .get();
+
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());
+
+ RoleResponse roleResponse = resp.readEntity(RoleResponse.class);
+ Assertions.assertEquals(0, roleResponse.getCode());
+ RoleDTO roleDTO = roleResponse.getRole();
+ Assertions.assertEquals("role1", roleDTO.name());
+ Assertions.assertTrue(role.properties().isEmpty());
+ Assertions.assertEquals(SecurableObjects.of("catalog"), roleDTO.securableObject());
+ Assertions.assertEquals(Lists.newArrayList(Privileges.LoadCatalog.get()), roleDTO.privileges());
+
+ // Test to throw NoSuchMetalakeException
+ doThrow(new NoSuchMetalakeException("mock error")).when(manager).loadRole(any(), any());
+ Response resp1 =
+ target("/metalakes/metalake1/roles/role1")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .get();
+
+ Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), resp1.getStatus());
+
+ ErrorResponse errorResponse = resp1.readEntity(ErrorResponse.class);
+ Assertions.assertEquals(ErrorConstants.NOT_FOUND_CODE, errorResponse.getCode());
+ Assertions.assertEquals(NoSuchMetalakeException.class.getSimpleName(), errorResponse.getType());
+
+ // Test to throw NoSuchRoleException
+ doThrow(new NoSuchRoleException("mock error")).when(manager).loadRole(any(), any());
+ Response resp2 =
+ target("/metalakes/metalake1/roles/role1")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .get();
+
+ Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), resp2.getStatus());
+
+ ErrorResponse errorResponse1 = resp2.readEntity(ErrorResponse.class);
+ Assertions.assertEquals(ErrorConstants.NOT_FOUND_CODE, errorResponse1.getCode());
+ Assertions.assertEquals(NoSuchRoleException.class.getSimpleName(), errorResponse1.getType());
+
+ // Test to throw internal RuntimeException
+ doThrow(new RuntimeException("mock error")).when(manager).loadRole(any(), any());
+ Response resp3 =
+ target("/metalakes/metalake1/roles/role1")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .get();
+
+ 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());
+ }
+
+ private Role buildRole(String role) {
+ return RoleEntity.builder()
+ .withId(1L)
+ .withName(role)
+ .withPrivileges(Lists.newArrayList(Privileges.LoadCatalog.get()))
+ .withProperties(Collections.emptyMap())
+ .withSecurableObject(SecurableObjects.of("catalog"))
+ .withAuditInfo(
+ AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build())
+ .build();
+ }
+
+ @Test
+ public void testDropRole() {
+ when(manager.dropRole(any(), any())).thenReturn(true);
+
+ Response resp =
+ target("/metalakes/metalake1/roles/role1")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .delete();
+
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus());
+ DropResponse dropResponse = resp.readEntity(DropResponse.class);
+ Assertions.assertEquals(0, dropResponse.getCode());
+ Assertions.assertTrue(dropResponse.dropped());
+
+ // Test when failed to drop role
+ when(manager.dropRole(any(), any())).thenReturn(false);
+ Response resp2 =
+ target("/metalakes/metalake1/roles/role1")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .delete();
+
+ Assertions.assertEquals(Response.Status.OK.getStatusCode(), resp2.getStatus());
+ DropResponse dropResponse2 = resp2.readEntity(DropResponse.class);
+ Assertions.assertEquals(0, dropResponse2.getCode());
+ Assertions.assertFalse(dropResponse2.dropped());
+
+ doThrow(new RuntimeException("mock error")).when(manager).dropRole(any(), any());
+ Response resp3 =
+ target("/metalakes/metalake1/roles/role1")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .delete();
+
+ 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());
+ }
+}