Skip to content

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

[#2234] feat(core): Add the support of User entity (#2481)

qqqttt1236641d70fdfce
diff --git a/api/src/main/java/com/datastrato/gravitino/authorization/User.java b/api/src/main/java/com/datastrato/gravitino/authorization/User.java
new file mode 100644
index 0000000000..32f57dd55a
--- /dev/null
+++ b/api/src/main/java/com/datastrato/gravitino/authorization/User.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.authorization;
+
+import com.datastrato.gravitino.Auditable;
+import com.datastrato.gravitino.annotation.Evolving;
+import java.util.List;
+
+/** The interface of a user. The user is the entity which executes every operation. */
+@Evolving
+public interface User extends Auditable {
+
+ /**
+ * The name of the user. It's the identifier of User. It must be unique. Usually the name comes
+ * from a external user management system like LDAP, IAM and so on.
+ *
+ * @return The name of the user.
+ */
+ String name();
+
+ /**
+ * The roles of the user. A user can have multiple roles. Every role binds several privileges.
+ *
+ * @return The roles of the user.
+ */
+ List<String> roles();
+}
diff --git a/api/src/main/java/com/datastrato/gravitino/exceptions/NoSuchUserException.java b/api/src/main/java/com/datastrato/gravitino/exceptions/NoSuchUserException.java
new file mode 100644
index 0000000000..7d7043166e
--- /dev/null
+++ b/api/src/main/java/com/datastrato/gravitino/exceptions/NoSuchUserException.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.exceptions;
+
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+
+/** An exception thrown when a user is not found. */
+public class NoSuchUserException extends NotFoundException {
+
+ /**
+ * Constructs a new exception with the specified detail message.
+ *
+ * @param message the detail message.
+ * @param args the arguments to the message.
+ */
+ @FormatMethod
+ public NoSuchUserException(@FormatString String message, Object... args) {
+ super(message, args);
+ }
+
+ /**
+ * Constructs a new exception with the specified detail message and cause.
+ *
+ * @param cause the cause.
+ * @param message the detail message.
+ * @param args the arguments to the message.
+ */
+ @FormatMethod
+ public NoSuchUserException(Throwable cause, String message, Object... args) {
+ super(cause, message, args);
+ }
+}
diff --git a/api/src/main/java/com/datastrato/gravitino/exceptions/UserAlreadyExistsException.java b/api/src/main/java/com/datastrato/gravitino/exceptions/UserAlreadyExistsException.java
new file mode 100644
index 0000000000..322897235c
--- /dev/null
+++ b/api/src/main/java/com/datastrato/gravitino/exceptions/UserAlreadyExistsException.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.exceptions;
+
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+
+/** An exception thrown when a user already exists. */
+public class UserAlreadyExistsException extends AlreadyExistsException {
+
+ /**
+ * Constructs a new exception with the specified detail message.
+ *
+ * @param message the detail message.
+ * @param args the arguments to the message.
+ */
+ @FormatMethod
+ public UserAlreadyExistsException(@FormatString String message, Object... args) {
+ super(message, args);
+ }
+
+ /**
+ * Constructs a new exception with the specified detail message and cause.
+ *
+ * @param cause the cause.
+ * @param message the detail message.
+ * @param args the arguments to the message.
+ */
+ @FormatMethod
+ public UserAlreadyExistsException(Throwable cause, String message, Object... args) {
+ super(cause, message, args);
+ }
+}
diff --git a/core/src/main/java/com/datastrato/gravitino/Entity.java b/core/src/main/java/com/datastrato/gravitino/Entity.java
index 116919fe62..95492996ee 100644
--- a/core/src/main/java/com/datastrato/gravitino/Entity.java
+++ b/core/src/main/java/com/datastrato/gravitino/Entity.java
@@ -21,6 +21,7 @@ public interface Entity extends Serializable {
COLUMN("co", 4),
FILESET("fi", 5),
TOPIC("to", 6),
+ USER("us", 7),
AUDIT("au", 65534);
diff --git a/core/src/main/java/com/datastrato/gravitino/GravitinoEnv.java b/core/src/main/java/com/datastrato/gravitino/GravitinoEnv.java
index a25398653e..7537a1e8d5 100644
--- a/core/src/main/java/com/datastrato/gravitino/GravitinoEnv.java
+++ b/core/src/main/java/com/datastrato/gravitino/GravitinoEnv.java
@@ -4,6 +4,7 @@
*/
package com.datastrato.gravitino;
+import com.datastrato.gravitino.authorization.AccessControlManager;
import com.datastrato.gravitino.auxiliary.AuxiliaryServiceManager;
import com.datastrato.gravitino.catalog.CatalogManager;
import com.datastrato.gravitino.catalog.CatalogOperationDispatcher;
@@ -35,6 +36,8 @@ public class GravitinoEnv {
private MetalakeManager metalakeManager;
+ private AccessControlManager accessControlManager;
+
private IdGenerator idGenerator;
private AuxiliaryServiceManager auxServiceManager;
@@ -97,6 +100,9 @@ public class GravitinoEnv {
this.catalogOperationDispatcher =
new CatalogOperationDispatcher(catalogManager, entityStore, idGenerator);
+ // Create and initialize access control related modules
+ this.accessControlManager = new AccessControlManager(entityStore, idGenerator);
+
this.auxServiceManager = new AuxiliaryServiceManager();
this.auxServiceManager.serviceInit(
config.getConfigsWithPrefix(AuxiliaryServiceManager.GRAVITINO_AUX_SERVICE_PREFIX));
@@ -174,6 +180,15 @@ public class GravitinoEnv {
return lockManager;
}
+ /**
+ * Get the AccessControlManager associated with the Gravitino environment.
+ *
+ * @return The AccessControlManager instance.
+ */
+ public AccessControlManager accessControlManager() {
+ return accessControlManager;
+ }
+
public void start() {
auxServiceManager.serviceStart();
metricsSystem.start();
diff --git a/core/src/main/java/com/datastrato/gravitino/authorization/AccessControlManager.java b/core/src/main/java/com/datastrato/gravitino/authorization/AccessControlManager.java
new file mode 100644
index 0000000000..0581df4ad7
--- /dev/null
+++ b/core/src/main/java/com/datastrato/gravitino/authorization/AccessControlManager.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.authorization;
+
+import com.datastrato.gravitino.EntityStore;
+import com.datastrato.gravitino.exceptions.NoSuchUserException;
+import com.datastrato.gravitino.exceptions.UserAlreadyExistsException;
+import com.datastrato.gravitino.storage.IdGenerator;
+
+/**
+ * AccessControlManager is used for manage users, roles, grant information, this class is an
+ * entrance class for tenant management.
+ */
+public class AccessControlManager {
+
+ private final UserManager userManager;
+
+ public AccessControlManager(EntityStore store, IdGenerator idGenerator) {
+ this.userManager = new UserManager(store, idGenerator);
+ }
+
+ /**
+ * Adds a new User.
+ *
+ * @param metalake The Metalake of the User.
+ * @param name The name of the User.
+ * @return The added User instance.
+ * @throws UserAlreadyExistsException If a User with the same identifier already exists.
+ * @throws RuntimeException If adding the User encounters storage issues.
+ */
+ public User addUser(String metalake, String name) throws UserAlreadyExistsException {
+ return userManager.addUser(metalake, name);
+ }
+
+ /**
+ * Removes a User.
+ *
+ * @param metalake The Metalake of the User.
+ * @param user THe name of the User.
+ * @return `true` if the User was successfully removed, `false` otherwise.
+ * @throws RuntimeException If removing the User encounters storage issues.
+ */
+ public boolean removeUser(String metalake, String user) {
+ return userManager.removeUser(metalake, user);
+ }
+
+ /**
+ * Gets a User.
+ *
+ * @param metalake The Metalake of the User.
+ * @param user The name of the User.
+ * @return The getting User instance.
+ * @throws NoSuchUserException If the User with the given identifier does not exist.
+ * @throws RuntimeException If getting the User encounters storage issues.
+ */
+ public User getUser(String metalake, String user) throws NoSuchUserException {
+ return userManager.getUser(metalake, user);
+ }
+}
diff --git a/core/src/main/java/com/datastrato/gravitino/authorization/UserManager.java b/core/src/main/java/com/datastrato/gravitino/authorization/UserManager.java
new file mode 100644
index 0000000000..a0fa164b33
--- /dev/null
+++ b/core/src/main/java/com/datastrato/gravitino/authorization/UserManager.java
@@ -0,0 +1,128 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.authorization;
+
+import com.datastrato.gravitino.Entity;
+import com.datastrato.gravitino.EntityAlreadyExistsException;
+import com.datastrato.gravitino.EntityStore;
+import com.datastrato.gravitino.NameIdentifier;
+import com.datastrato.gravitino.Namespace;
+import com.datastrato.gravitino.exceptions.NoSuchEntityException;
+import com.datastrato.gravitino.exceptions.NoSuchUserException;
+import com.datastrato.gravitino.exceptions.UserAlreadyExistsException;
+import com.datastrato.gravitino.meta.AuditInfo;
+import com.datastrato.gravitino.meta.CatalogEntity;
+import com.datastrato.gravitino.meta.UserEntity;
+import com.datastrato.gravitino.storage.IdGenerator;
+import com.datastrato.gravitino.utils.PrincipalUtils;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * UserManager is used for add, remove and get users from one metalake. UserManager doesn't manage
+ * users, just sets up the relationship between the metalake and the user. Metalake is like a
+ * concept of the organization. `AddUser` means that a user enter an organization.
+ */
+public class UserManager {
+
+ private static final Logger LOG = LoggerFactory.getLogger(UserManager.class);
+ private static final String USER_DOES_NOT_EXIST_MSG = "User %s does not exist in th metalake %s";
+
+ private final EntityStore store;
+ private final IdGenerator idGenerator;
+
+ public UserManager(EntityStore store, IdGenerator idGenerator) {
+ this.store = store;
+ this.idGenerator = idGenerator;
+ }
+
+ /**
+ * Adds a new User.
+ *
+ * @param metalake The Metalake of the User.
+ * @param name The name of the User.
+ * @return The added User instance.
+ * @throws UserAlreadyExistsException If a User with the same identifier already exists.
+ * @throws RuntimeException If adding the User encounters storage issues.
+ */
+ public User addUser(String metalake, String name) throws UserAlreadyExistsException {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(idGenerator.nextId())
+ .withName(name)
+ .withNamespace(
+ Namespace.of(
+ metalake,
+ CatalogEntity.SYSTEM_CATALOG_RESERVED_NAME,
+ UserEntity.USER_SCHEMA_NAME))
+ .withRoles(Lists.newArrayList())
+ .withAuditInfo(
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build())
+ .build();
+ try {
+ store.put(userEntity, false /* overwritten */);
+ return userEntity;
+ } catch (EntityAlreadyExistsException e) {
+ LOG.warn("User {} in the metalake {} already exists", name, metalake, e);
+ throw new UserAlreadyExistsException(
+ "User %s in the metalake %s already exists", name, metalake);
+ } catch (IOException ioe) {
+ LOG.error(
+ "Adding user {} failed in the metalake {} due to storage issues", name, metalake, ioe);
+ throw new RuntimeException(ioe);
+ }
+ }
+
+ /**
+ * Removes a User.
+ *
+ * @param metalake The Metalake of the User.
+ * @param user THe name of the User.
+ * @return `true` if the User was successfully removed, `false` otherwise.
+ * @throws RuntimeException If removing the User encounters storage issues.
+ */
+ public boolean removeUser(String metalake, String user) {
+
+ try {
+ return store.delete(ofUser(metalake, user), Entity.EntityType.USER);
+ } catch (IOException ioe) {
+ LOG.error(
+ "Removing user {} in the metalake {} failed due to storage issues", user, metalake, ioe);
+ throw new RuntimeException(ioe);
+ }
+ }
+
+ /**
+ * Gets a User.
+ *
+ * @param metalake The Metalake of the User.
+ * @param user The name of the User.
+ * @return The getting User instance.
+ * @throws NoSuchUserException If the User with the given identifier does not exist.
+ * @throws RuntimeException If getting the User encounters storage issues.
+ */
+ public User getUser(String metalake, String user) throws NoSuchUserException {
+ try {
+ return store.get(ofUser(metalake, user), Entity.EntityType.USER, UserEntity.class);
+ } catch (NoSuchEntityException e) {
+ LOG.warn("User {} does not exist in the metalake {}", user, metalake, e);
+ throw new NoSuchUserException(USER_DOES_NOT_EXIST_MSG, user, metalake);
+ } catch (IOException ioe) {
+ LOG.error("Getting user {} failed due to storage issues", user, ioe);
+ throw new RuntimeException(ioe);
+ }
+ }
+
+ private NameIdentifier ofUser(String metalake, String user) {
+ return NameIdentifier.of(
+ metalake, CatalogEntity.SYSTEM_CATALOG_RESERVED_NAME, UserEntity.USER_SCHEMA_NAME, user);
+ }
+}
diff --git a/core/src/main/java/com/datastrato/gravitino/catalog/CatalogManager.java b/core/src/main/java/com/datastrato/gravitino/catalog/CatalogManager.java
index 40bccd9130..7f7a718e5e 100644
--- a/core/src/main/java/com/datastrato/gravitino/catalog/CatalogManager.java
+++ b/core/src/main/java/com/datastrato/gravitino/catalog/CatalogManager.java
@@ -272,6 +272,10 @@ public class CatalogManager implements SupportsCatalogs, Closeable {
Map<String, String> properties)
throws NoSuchMetalakeException, CatalogAlreadyExistsException {
+ if (CatalogEntity.SYSTEM_CATALOG_RESERVED_NAME.equals(ident.name())) {
+ throw new IllegalArgumentException("Can't create a catalog with with reserved name `system`");
+ }
+
// load catalog-related configuration from catalog-specific configuration file
Map<String, String> catalogSpecificConfig = loadCatalogSpecificConfig(properties, provider);
Map<String, String> mergedConfig = mergeConf(properties, catalogSpecificConfig);
@@ -658,6 +662,13 @@ public class CatalogManager implements SupportsCatalogs, Closeable {
for (CatalogChange change : changes) {
if (change instanceof CatalogChange.RenameCatalog) {
CatalogChange.RenameCatalog rename = (CatalogChange.RenameCatalog) change;
+
+ if (CatalogEntity.SYSTEM_CATALOG_RESERVED_NAME.equals(
+ ((CatalogChange.RenameCatalog) change).getNewName())) {
+ throw new IllegalArgumentException(
+ "Can't rename a catalog with with reserved name `system`");
+ }
+
builder.withName(rename.getNewName());
} else if (change instanceof CatalogChange.UpdateCatalogComment) {
diff --git a/core/src/main/java/com/datastrato/gravitino/meta/CatalogEntity.java b/core/src/main/java/com/datastrato/gravitino/meta/CatalogEntity.java
index 28b270a103..606555fc82 100644
--- a/core/src/main/java/com/datastrato/gravitino/meta/CatalogEntity.java
+++ b/core/src/main/java/com/datastrato/gravitino/meta/CatalogEntity.java
@@ -24,6 +24,8 @@ import lombok.ToString;
@ToString
public class CatalogEntity implements Entity, Auditable, HasIdentifier {
+ public static final String SYSTEM_CATALOG_RESERVED_NAME = "system";
+
public static final Field ID =
Field.required("id", Long.class, "The catalog's unique identifier");
public static final Field NAME = Field.required("name", String.class, "The catalog's name");
diff --git a/core/src/main/java/com/datastrato/gravitino/meta/UserEntity.java b/core/src/main/java/com/datastrato/gravitino/meta/UserEntity.java
new file mode 100644
index 0000000000..f6d9f05b93
--- /dev/null
+++ b/core/src/main/java/com/datastrato/gravitino/meta/UserEntity.java
@@ -0,0 +1,214 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.meta;
+
+import com.datastrato.gravitino.Auditable;
+import com.datastrato.gravitino.Entity;
+import com.datastrato.gravitino.Field;
+import com.datastrato.gravitino.HasIdentifier;
+import com.datastrato.gravitino.Namespace;
+import com.datastrato.gravitino.authorization.User;
+import com.google.common.collect.Maps;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import lombok.ToString;
+
+/** A class representing a user metadata entity in Gravitino. */
+@ToString
+public class UserEntity implements User, Entity, Auditable, HasIdentifier {
+
+ public static final String USER_SCHEMA_NAME = "user";
+
+ public static final Field ID =
+ Field.required("id", Long.class, " The unique id of the user entity.");
+
+ public static final Field NAME =
+ Field.required("name", String.class, "The name of the user entity.");
+
+ public static final Field AUDIT_INFO =
+ Field.required("audit_info", AuditInfo.class, "The audit details of the user entity.");
+
+ public static final Field ROLES =
+ Field.optional("roles", List.class, "The roles of the user entity");
+
+ private Long id;
+ private String name;
+ private AuditInfo auditInfo;
+ private List<String> roles;
+ private Namespace namespace;
+
+ private UserEntity() {}
+
+ /**
+ * Returns a map of fields and their corresponding values for this user entity.
+ *
+ * @return An unmodifiable map of the fields and values.
+ */
+ @Override
+ public Map<Field, Object> fields() {
+ Map<Field, Object> fields = Maps.newHashMap();
+ fields.put(ID, id);
+ fields.put(NAME, name);
+ fields.put(AUDIT_INFO, auditInfo);
+ fields.put(ROLES, roles);
+
+ return Collections.unmodifiableMap(fields);
+ }
+
+ /**
+ * Returns the name of the user.
+ *
+ * @return The name of the user.
+ */
+ @Override
+ public String name() {
+ return name;
+ }
+
+ /**
+ * Returns the unique id of the user.
+ *
+ * @return The unique id of the user.
+ */
+ @Override
+ public Long id() {
+ return id;
+ }
+
+ /**
+ * Returns the type of the entity.
+ *
+ * @return The type of the entity.
+ */
+ @Override
+ public EntityType type() {
+ return EntityType.USER;
+ }
+
+ /**
+ * Returns the namespace of the user.
+ *
+ * @return The namespace of the user.
+ */
+ @Override
+ public Namespace namespace() {
+ return namespace;
+ }
+
+ /**
+ * Returns the audit details of the user.
+ *
+ * @return The audit details of the user.
+ */
+ public AuditInfo auditInfo() {
+ return auditInfo;
+ }
+
+ /**
+ * The roles of the user.
+ *
+ * @return The roles of the user.
+ */
+ @Override
+ public List<String> roles() {
+ return roles;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof UserEntity)) return false;
+
+ UserEntity that = (UserEntity) o;
+ return Objects.equals(id, that.id)
+ && Objects.equals(name, that.name)
+ && Objects.equals(auditInfo, that.auditInfo)
+ && Objects.equals(roles, that.roles);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(id, name, auditInfo, roles);
+ }
+
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public static class Builder {
+ private final UserEntity userEntity;
+
+ private Builder() {
+ this.userEntity = new UserEntity();
+ }
+
+ /**
+ * Sets the unique id of the user entity.
+ *
+ * @param id The unique id of the user entity.
+ * @return The builder instance.
+ */
+ public Builder withId(Long id) {
+ userEntity.id = id;
+ return this;
+ }
+
+ /**
+ * Sets the name of the user entity.
+ *
+ * @param name The name of the user entity.
+ * @return The builder instance.
+ */
+ public Builder withName(String name) {
+ userEntity.name = name;
+ return this;
+ }
+
+ /**
+ * Sets the audit details of the user entity.
+ *
+ * @param auditInfo The audit details of the user entity.
+ * @return The builder instance.
+ */
+ public Builder withAuditInfo(AuditInfo auditInfo) {
+ userEntity.auditInfo = auditInfo;
+ return this;
+ }
+
+ /**
+ * Sets the roles of the user entity.
+ *
+ * @param roles The roles of the user entity.
+ * @return The builder instance.
+ */
+ public Builder withRoles(List<String> roles) {
+ userEntity.roles = roles;
+ return this;
+ }
+
+ /**
+ * Sets the namespace of the user entity.
+ *
+ * @param namespace The namespace of the user entity.
+ * @return The builder instance.
+ */
+ public Builder withNamespace(Namespace namespace) {
+ userEntity.namespace = namespace;
+ return this;
+ }
+
+ /**
+ * Builds the user entity.
+ *
+ * @return The built user entity.
+ */
+ public UserEntity build() {
+ userEntity.validate();
+ return userEntity;
+ }
+ }
+}
diff --git a/core/src/main/java/com/datastrato/gravitino/proto/ProtoEntitySerDe.java b/core/src/main/java/com/datastrato/gravitino/proto/ProtoEntitySerDe.java
index 182716cbfc..a346a5cd9d 100644
--- a/core/src/main/java/com/datastrato/gravitino/proto/ProtoEntitySerDe.java
+++ b/core/src/main/java/com/datastrato/gravitino/proto/ProtoEntitySerDe.java
@@ -40,6 +40,9 @@ public class ProtoEntitySerDe implements EntitySerDe {
.put(
"com.datastrato.gravitino.meta.TopicEntity",
"com.datastrato.gravitino.proto.TopicEntitySerDe")
+ .put(
+ "com.datastrato.gravitino.meta.UserEntity",
+ "com.datastrato.gravitino.proto.UserEntitySerDe")
.build();
private static final Map<String, String> ENTITY_TO_PROTO =
@@ -57,7 +60,9 @@ public class ProtoEntitySerDe implements EntitySerDe {
"com.datastrato.gravitino.meta.FilesetEntity",
"com.datastrato.gravitino.proto.Fileset",
"com.datastrato.gravitino.meta.TopicEntity",
- "com.datastrato.gravitino.proto.Topic");
+ "com.datastrato.gravitino.proto.Topic",
+ "com.datastrato.gravitino.meta.UserEntity",
+ "com.datastrato.gravitino.proto.User");
private final Map<Class<? extends Entity>, ProtoSerDe<? extends Entity, ? extends Message>>
entityToSerDe;
diff --git a/core/src/main/java/com/datastrato/gravitino/proto/UserEntitySerDe.java b/core/src/main/java/com/datastrato/gravitino/proto/UserEntitySerDe.java
new file mode 100644
index 0000000000..e87f331436
--- /dev/null
+++ b/core/src/main/java/com/datastrato/gravitino/proto/UserEntitySerDe.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.proto;
+
+import com.datastrato.gravitino.meta.UserEntity;
+import java.util.Collection;
+
+public class UserEntitySerDe implements ProtoSerDe<UserEntity, User> {
+
+ @Override
+ public User serialize(UserEntity userEntity) {
+ User.Builder builder =
+ User.newBuilder()
+ .setId(userEntity.id())
+ .setName(userEntity.name())
+ .setAuditInfo(new AuditInfoSerDe().serialize(userEntity.auditInfo()));
+
+ if (isCollectionNotEmpty(userEntity.roles())) {
+ builder.addAllRoles(userEntity.roles());
+ }
+
+ return builder.build();
+ }
+
+ @Override
+ public UserEntity deserialize(User user) {
+ UserEntity.Builder builder =
+ UserEntity.builder()
+ .withId(user.getId())
+ .withName(user.getName())
+ .withAuditInfo(new AuditInfoSerDe().deserialize(user.getAuditInfo()));
+
+ if (user.getRolesCount() > 0) {
+ builder.withRoles(user.getRolesList());
+ }
+
+ return builder.build();
+ }
+
+ private boolean isCollectionNotEmpty(Collection collection) {
+ return collection != null && !collection.isEmpty();
+ }
+}
diff --git a/core/src/main/java/com/datastrato/gravitino/storage/kv/BinaryEntityKeyEncoder.java b/core/src/main/java/com/datastrato/gravitino/storage/kv/BinaryEntityKeyEncoder.java
index 0e89f17522..e6096af372 100644
--- a/core/src/main/java/com/datastrato/gravitino/storage/kv/BinaryEntityKeyEncoder.java
+++ b/core/src/main/java/com/datastrato/gravitino/storage/kv/BinaryEntityKeyEncoder.java
@@ -9,6 +9,7 @@ import static com.datastrato.gravitino.Entity.EntityType.FILESET;
import static com.datastrato.gravitino.Entity.EntityType.METALAKE;
import static com.datastrato.gravitino.Entity.EntityType.SCHEMA;
import static com.datastrato.gravitino.Entity.EntityType.TABLE;
+import static com.datastrato.gravitino.Entity.EntityType.USER;
import com.datastrato.gravitino.Entity.EntityType;
import com.datastrato.gravitino.NameIdentifier;
@@ -66,11 +67,18 @@ public class BinaryEntityKeyEncoder implements EntityKeyEncoder<byte[]> {
// Key format template. Please the comment of the class for more details.
public static final Map<EntityType, String[]> ENTITY_TYPE_TO_NAME_IDENTIFIER =
ImmutableMap.of(
- METALAKE, new String[] {METALAKE.getShortName() + "/"},
- CATALOG, new String[] {CATALOG.getShortName() + "/", "/"},
- SCHEMA, new String[] {SCHEMA.getShortName() + "/", "/", "/"},
- TABLE, new String[] {TABLE.getShortName() + "/", "/", "/", "/"},
- FILESET, new String[] {FILESET.getShortName() + "/", "/", "/", "/"});
+ METALAKE,
+ new String[] {METALAKE.getShortName() + "/"},
+ CATALOG,
+ new String[] {CATALOG.getShortName() + "/", "/"},
+ SCHEMA,
+ new String[] {SCHEMA.getShortName() + "/", "/", "/"},
+ TABLE,
+ new String[] {TABLE.getShortName() + "/", "/", "/", "/"},
+ FILESET,
+ new String[] {FILESET.getShortName() + "/", "/", "/", "/"},
+ USER,
+ new String[] {USER.getShortName() + "/", "/", "/", "/"});
@VisibleForTesting final NameMappingService nameMappingService;
diff --git a/core/src/main/java/com/datastrato/gravitino/storage/kv/KvEntityStore.java b/core/src/main/java/com/datastrato/gravitino/storage/kv/KvEntityStore.java
index 974412404f..e79d679269 100644
--- a/core/src/main/java/com/datastrato/gravitino/storage/kv/KvEntityStore.java
+++ b/core/src/main/java/com/datastrato/gravitino/storage/kv/KvEntityStore.java
@@ -8,8 +8,10 @@ package com.datastrato.gravitino.storage.kv;
import static com.datastrato.gravitino.Configs.ENTITY_KV_STORE;
import static com.datastrato.gravitino.Entity.EntityType.CATALOG;
import static com.datastrato.gravitino.Entity.EntityType.FILESET;
+import static com.datastrato.gravitino.Entity.EntityType.METALAKE;
import static com.datastrato.gravitino.Entity.EntityType.SCHEMA;
import static com.datastrato.gravitino.Entity.EntityType.TABLE;
+import static com.datastrato.gravitino.Entity.EntityType.USER;
import static com.datastrato.gravitino.storage.kv.BinaryEntityKeyEncoder.LOG;
import static com.datastrato.gravitino.storage.kv.BinaryEntityKeyEncoder.NAMESPACE_SEPARATOR;
@@ -332,6 +334,20 @@ public class KvEntityStore implements EntityStore {
return prefixes;
}
+ void deleteUserEntitiesIfNecessary(NameIdentifier ident, EntityType type) throws IOException {
+ if (type != METALAKE) {
+ return;
+ }
+ byte[] encode = entityKeyEncoder.encode(ident, type, true);
+ byte[] prefix = replacePrefixTypeInfo(encode, USER.getShortName());
+ transactionalKvBackend.deleteRange(
+ new KvRange.KvRangeBuilder()
+ .start(prefix)
+ .startInclusive(true)
+ .end(Bytes.increment(Bytes.wrap(prefix)).get())
+ .build());
+ }
+
private byte[] replacePrefixTypeInfo(byte[] encode, String subTypePrefix) {
byte[] result = new byte[encode.length];
System.arraycopy(encode, 0, result, 0, encode.length);
@@ -390,6 +406,7 @@ public class KvEntityStore implements EntityStore {
.build());
}
+ deleteUserEntitiesIfNecessary(ident, entityType);
return transactionalKvBackend.delete(dataKey);
});
}
diff --git a/core/src/test/java/com/datastrato/gravitino/authorization/TestAccessControlManager.java b/core/src/test/java/com/datastrato/gravitino/authorization/TestAccessControlManager.java
new file mode 100644
index 0000000000..eaa0081fcf
--- /dev/null
+++ b/core/src/test/java/com/datastrato/gravitino/authorization/TestAccessControlManager.java
@@ -0,0 +1,109 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.authorization;
+
+import com.datastrato.gravitino.Config;
+import com.datastrato.gravitino.EntityStore;
+import com.datastrato.gravitino.exceptions.NoSuchUserException;
+import com.datastrato.gravitino.exceptions.UserAlreadyExistsException;
+import com.datastrato.gravitino.meta.AuditInfo;
+import com.datastrato.gravitino.meta.BaseMetalake;
+import com.datastrato.gravitino.meta.SchemaVersion;
+import com.datastrato.gravitino.storage.RandomIdGenerator;
+import com.datastrato.gravitino.storage.memory.TestMemoryEntityStore;
+import java.io.IOException;
+import java.time.Instant;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+public class TestAccessControlManager {
+
+ private static AccessControlManager accessControlManager;
+
+ private static EntityStore entityStore;
+
+ private static Config config;
+
+ private static String metalake = "metalake";
+
+ private static BaseMetalake metalakeEntity =
+ BaseMetalake.builder()
+ .withId(1L)
+ .withName(metalake)
+ .withAuditInfo(
+ AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build())
+ .withVersion(SchemaVersion.V_0_1)
+ .build();
+
+ @BeforeAll
+ public static void setUp() throws Exception {
+ config = new Config(false) {};
+
+ entityStore = new TestMemoryEntityStore.InMemoryEntityStore();
+ entityStore.initialize(config);
+ entityStore.setSerDe(null);
+
+ entityStore.put(metalakeEntity, true);
+
+ accessControlManager = new AccessControlManager(entityStore, new RandomIdGenerator());
+ }
+
+ @AfterAll
+ public static void tearDown() throws IOException {
+ if (entityStore != null) {
+ entityStore.close();
+ entityStore = null;
+ }
+ }
+
+ @Test
+ public void testAddUser() {
+
+ User user = accessControlManager.addUser("metalake", "testAdd");
+ Assertions.assertEquals("testAdd", user.name());
+ Assertions.assertTrue(user.roles().isEmpty());
+
+ user = accessControlManager.addUser("metalake", "testAddWithOptionalField");
+
+ Assertions.assertEquals("testAddWithOptionalField", user.name());
+ Assertions.assertTrue(user.roles().isEmpty());
+
+ // Test with UserAlreadyExistsException
+ Assertions.assertThrows(
+ UserAlreadyExistsException.class,
+ () -> accessControlManager.addUser("metalake", "testAdd"));
+ }
+
+ @Test
+ public void testGetUser() {
+
+ accessControlManager.addUser("metalake", "testGet");
+
+ User user = accessControlManager.getUser("metalake", "testGet");
+ Assertions.assertEquals("testGet", user.name());
+
+ // Test to get non-existed user
+ Throwable exception =
+ Assertions.assertThrows(
+ NoSuchUserException.class, () -> accessControlManager.getUser("metalake", "not-exist"));
+ Assertions.assertTrue(exception.getMessage().contains("User not-exist does not exist"));
+ }
+
+ @Test
+ public void testRemoveUser() {
+
+ accessControlManager.addUser("metalake", "testRemove");
+
+ // Test to remove user
+ boolean dropped = accessControlManager.removeUser("metalake", "testRemove");
+ Assertions.assertTrue(dropped);
+
+ // Test to remove non-existed user
+ boolean dropped1 = accessControlManager.removeUser("metalake", "no-exist");
+ Assertions.assertFalse(dropped1);
+ }
+}
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 36de1404d6..94c6b7fd96 100644
--- a/core/src/test/java/com/datastrato/gravitino/meta/TestEntity.java
+++ b/core/src/test/java/com/datastrato/gravitino/meta/TestEntity.java
@@ -8,6 +8,7 @@ import com.datastrato.gravitino.Catalog;
import com.datastrato.gravitino.Field;
import com.datastrato.gravitino.file.Fileset;
import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
import java.time.Instant;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
@@ -47,6 +48,10 @@ public class TestEntity {
private final Long topicId = 1L;
private final String topicName = "testTopic";
+ // User test data
+ private final Long userId = 1L;
+ private final String userName = "testUser";
+
@Test
public void testMetalake() {
BaseMetalake metalake =
@@ -200,4 +205,26 @@ public class TestEntity {
Assertions.assertNull(testTopic1.comment());
Assertions.assertNull(testTopic1.properties());
}
+
+ @Test
+ public void testUser() {
+ UserEntity testUserEntity =
+ UserEntity.builder()
+ .withId(userId)
+ .withName(userName)
+ .withAuditInfo(auditInfo)
+ .withRoles(Lists.newArrayList("role"))
+ .build();
+
+ Map<Field, Object> fields = testUserEntity.fields();
+ Assertions.assertEquals(userId, fields.get(UserEntity.ID));
+ Assertions.assertEquals(userName, fields.get(UserEntity.NAME));
+ Assertions.assertEquals(auditInfo, fields.get(UserEntity.AUDIT_INFO));
+ Assertions.assertEquals(Lists.newArrayList("role"), fields.get(UserEntity.ROLES));
+
+ UserEntity testUserEntityWithoutFields =
+ UserEntity.builder().withId(userId).withName(userName).withAuditInfo(auditInfo).build();
+
+ Assertions.assertNull(testUserEntityWithoutFields.roles());
+ }
}
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 cd8649f47f..8c8a50d454 100644
--- a/core/src/test/java/com/datastrato/gravitino/proto/TestEntityProtoSerDe.java
+++ b/core/src/test/java/com/datastrato/gravitino/proto/TestEntityProtoSerDe.java
@@ -7,7 +7,9 @@ package com.datastrato.gravitino.proto;
import com.datastrato.gravitino.EntitySerDe;
import com.datastrato.gravitino.EntitySerDeFactory;
import com.datastrato.gravitino.meta.SchemaVersion;
+import com.datastrato.gravitino.meta.UserEntity;
import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
import java.io.IOException;
import java.time.Instant;
import java.util.Map;
@@ -274,5 +276,25 @@ public class TestEntityProtoSerDe {
Assertions.assertEquals(topicEntity1, topicEntityFromBytes1);
Assertions.assertNull(topicEntityFromBytes1.comment());
Assertions.assertNull(topicEntityFromBytes1.properties());
+
+ // Test UserEntity
+ Long userId = 1L;
+ String userName = "user";
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(userId)
+ .withName(userName)
+ .withAuditInfo(auditInfo)
+ .withRoles(Lists.newArrayList("role"))
+ .build();
+ byte[] userBytes = protoEntitySerDe.serialize(userEntity);
+ UserEntity userEntityFromBytes = protoEntitySerDe.deserialize(userBytes, UserEntity.class);
+ Assertions.assertEquals(userEntity, userEntityFromBytes);
+
+ UserEntity userEntityWithoutFields =
+ UserEntity.builder().withId(userId).withName(userName).withAuditInfo(auditInfo).build();
+ userBytes = protoEntitySerDe.serialize(userEntityWithoutFields);
+ userEntityFromBytes = protoEntitySerDe.deserialize(userBytes, UserEntity.class);
+ Assertions.assertEquals(userEntityWithoutFields, userEntityFromBytes);
}
}
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 7d4fbb6afe..3aa0bef0da 100644
--- a/core/src/test/java/com/datastrato/gravitino/storage/TestEntityStorage.java
+++ b/core/src/test/java/com/datastrato/gravitino/storage/TestEntityStorage.java
@@ -38,9 +38,11 @@ import com.datastrato.gravitino.meta.FilesetEntity;
import com.datastrato.gravitino.meta.SchemaEntity;
import com.datastrato.gravitino.meta.SchemaVersion;
import com.datastrato.gravitino.meta.TableEntity;
+import com.datastrato.gravitino.meta.UserEntity;
import com.datastrato.gravitino.storage.relational.RelationalEntityStore;
import com.datastrato.gravitino.storage.relational.session.SqlSessionFactoryHelper;
import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@@ -58,6 +60,7 @@ import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.Mockito;
@@ -377,6 +380,34 @@ public class TestEntityStorage {
}
}
+ @ParameterizedTest
+ @MethodSource("storageProvider")
+ public void testUserEntityDelete(String type) throws IOException {
+ // User entity only supports kv store.
+ Assumptions.assumeTrue(Configs.DEFAULT_ENTITY_STORE.equals(type));
+ Config config = Mockito.mock(Config.class);
+ init(type, config);
+
+ AuditInfo auditInfo =
+ AuditInfo.builder().withCreator("creator").withCreateTime(Instant.now()).build();
+
+ try (EntityStore store = EntityStoreFactory.createEntityStore(config)) {
+ store.initialize(config);
+
+ BaseMetalake metalake = createBaseMakeLake(1L, "metalake", auditInfo);
+ store.put(metalake);
+ UserEntity oneUser = createUser("metalake", "oneUser", auditInfo);
+ store.put(oneUser);
+ UserEntity anotherUser = createUser("metalake", "anotherUser", auditInfo);
+ store.put(anotherUser);
+ Assertions.assertTrue(store.exists(oneUser.nameIdentifier(), Entity.EntityType.USER));
+ Assertions.assertTrue(store.exists(anotherUser.nameIdentifier(), Entity.EntityType.USER));
+ store.delete(metalake.nameIdentifier(), Entity.EntityType.METALAKE);
+ Assertions.assertFalse(store.exists(oneUser.nameIdentifier(), Entity.EntityType.USER));
+ Assertions.assertFalse(store.exists(anotherUser.nameIdentifier(), Entity.EntityType.USER));
+ }
+ }
+
@ParameterizedTest
@MethodSource("storageProvider")
void testEntityDelete(String type) throws IOException {
@@ -829,6 +860,18 @@ public class TestEntityStorage {
.build();
}
+ private static UserEntity createUser(String metalake, String name, AuditInfo auditInfo) {
+ return UserEntity.builder()
+ .withId(1L)
+ .withNamespace(
+ Namespace.of(
+ metalake, CatalogEntity.SYSTEM_CATALOG_RESERVED_NAME, UserEntity.USER_SCHEMA_NAME))
+ .withName(name)
+ .withAuditInfo(auditInfo)
+ .withRoles(Lists.newArrayList())
+ .build();
+ }
+
private void validateDeleteFilesetCascade(EntityStore store, FilesetEntity fileset1)
throws IOException {
// Delete the fileset 'metalake.catalog.schema1.fileset1'
diff --git a/meta/src/main/proto/gravitino_meta.proto b/meta/src/main/proto/gravitino_meta.proto
index 2f7d6f9e15..5468cfab25 100644
--- a/meta/src/main/proto/gravitino_meta.proto
+++ b/meta/src/main/proto/gravitino_meta.proto
@@ -101,3 +101,10 @@ message Topic {
map<string, string> properties = 4;
AuditInfo audit_info = 5;
}
+
+message User {
+ uint64 id = 1;
+ string name = 2;
+ repeated string roles = 3;
+ AuditInfo audit_info = 4;
+}