You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@gravitino.apache.org by "xunliu (via GitHub)" <gi...@apache.org> on 2024/08/14 11:18:20 UTC
[PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
xunliu opened a new pull request, #4515:
URL: https://github.com/apache/gravitino/pull/4515
### What changes were proposed in this pull request?
Use Gravitino authorization plugin to authorize Ranger Hive.
1. Added RangerHiveAuthorization modul
2. Added Ranger client extension
### Why are the changes needed?
Fix: #3963
### Does this PR introduce _any_ user-facing change?
1. Added RangerHiveAuthorizationPlugin interface
### How was this patch tested?
RangerAuthorizationHiveIT passed.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "lw-yang (via GitHub)" <gi...@apache.org>.
lw-yang commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1722591836
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1015 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
Review Comment:
I mean if the policy exists but the policyItem does not exit, we should add a policyItem.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1015 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ // Find match policy item and set the role
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return execResult.get();
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
Review Comment:
We should remove this policy modification, keep align with `grantRoleToUser`
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1015 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ // Find match policy item and set the role
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return execResult.get();
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy is not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilege -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilege))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+ return execResult.get();
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ mapAccesses.put(access.getType(), true);
+ });
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy exists but has different privileges, also return true. Because one Ranger
+ * policy maybe contain multiple Gravitino securable object <br>
+ * 4. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravition securable object's privilege
+ // and roleName
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If exist policy and have same privilege then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(change.getSecurableObject().fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(
+ SecurableObjects.DOT_SPLITTER.splitToList(change.getSecurableObject().fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+ }
+
+ addPolicyItem(policy, change.getRoleName(), change.getSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return true;
+ }
+
+ /**
+ * Remove the securable object's privilege from the policy. <br>
+ * Because Ranger use unique metadata to location Ranger policy and manage the all privileges, So
+ * one Ranger policy maybe contain multiple Gravitino privilege objects. <br>
+ * Remove Ranger policy item condition is: <br>
+ * 1. This Ranger policy item's accesses equal the Gravition securable object's privilege. <br>
+ * 2. This Ranger policy item's users and groups is empty. <br>
+ * If policy didn't have any policy item, then delete this policy: <br>
+ */
+ private boolean doRemoveSecurableObject(
+ String roleName, RoleChange.RemoveSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ policy
+ .getPolicyItems()
+ .forEach(
+ policyItem -> {
+ boolean match =
+ policyItem.getAccesses().stream()
+ .allMatch(
+ // Find the policy item that match access and role
+ access -> {
+ // Use Gravitino privilege to search the Ranger policy item's access
+ boolean matchPrivilege =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(
+ privilege ->
+ translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .anyMatch(privilege -> privilege.equals(access.getType()));
+ return matchPrivilege;
+ });
+ if (match) {
+ policyItem.getRoles().removeIf(roleName::equals);
+ }
+ });
+
+ // If the policy does have any role and user and group, then remove it.
+ policy
+ .getPolicyItems()
+ .removeIf(
+ policyItem ->
+ policyItem.getRoles().isEmpty()
+ && policyItem.getUsers().isEmpty()
+ && policyItem.getGroups().isEmpty());
+
+ try {
+ if (policy.getPolicyItems().size() == 0) {
+ rangerClient.deletePolicy(policy.getId());
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ LOG.error("Failed to remove the policy item from the Ranger policy {}!", policy);
+ throw new RuntimeException(e);
+ }
+ } else {
+ LOG.warn(
+ "Cannot find the Ranger policy({}) for the Gravitino securable object({})!",
+ roleName,
+ change.getSecurableObject().fullName());
+ // Don't throw exception or return false, because need support immutable operation.
+ }
+ return true;
+ }
+
+ /**
+ * 1. Find the policy base securable object. <br>
+ * 2. If the policy is exist, then user new securable object's privilege to update. <br>
+ * 3. If the policy is not exist return false. <br>
+ */
+ private boolean doUpdateSecurableObject(
+ String roleName, RoleChange.UpdateSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ removePolicyItem(policy, roleName, change.getSecurableObject());
+ addPolicyItem(policy, roleName, change.getNewSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ } else {
+ LOG.warn(
+ "Cannot find the policy({}) for the securable object({})!",
+ roleName,
+ change.getSecurableObject().fullName());
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Add policy item access items base the securable object's privileges. <br>
+ * We didn't clean the policy items, because one Ranger policy maybe contain multiple Gravitino
+ * securable objects. <br>
+ */
+ private void addPolicyItem(
+ RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkSecurableObject(securableObject);
+
+ // Add the policy items by the securable object's privileges
+ securableObject
+ .privileges()
+ .forEach(
+ gravitinoPrivilege -> {
+ // Translate the Gravitino privilege to mapped Ranger privilege
+ translatePrivilege(gravitinoPrivilege.name())
+ .forEach(
+ mappedPrivilege -> {
+ // Find the policy item that match access and role
+ boolean exist =
+ policy.getPolicyItems().stream()
+ .anyMatch(
+ policyItem -> {
+ return policyItem.getRoles().contains(roleName)
+ && policyItem.getAccesses().stream()
+ .anyMatch(
+ access ->
+ access.getType().equals(mappedPrivilege));
+ });
+ if (exist) {
+ return;
+ }
+
+ RangerPolicy.RangerPolicyItem policyItem =
+ new RangerPolicy.RangerPolicyItem();
+ RangerPolicy.RangerPolicyItemAccess access =
+ new RangerPolicy.RangerPolicyItemAccess();
Review Comment:
But the current logic doesn't seem to be like that.
If the condition is true, we should update this policyItem.
```
policyItem.getAccesses().stream().anyMatch(access ->access.getType().equals(mappedPrivilege))
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1721287928
##########
integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/RangerContainer.java:
##########
@@ -40,15 +40,18 @@ public class RangerContainer extends BaseContainer {
public static final int RANGER_SERVER_PORT = 6080;
public RangerClient rangerClient;
private String rangerUrl;
- private static final String username = "admin";
- // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
- private static final String password = "rangerR0cks!";
/**
- * for kerberos authentication: authType = "kerberos" username = principal password = path of the
- * keytab file
+ * for kerberos authentication: <br>
+ * authType = "kerberos" <br>
+ * username = principal <br>
+ * password = path of the keytab file <br>
*/
- private static final String authType = "simple";
+ public static final String authType = "simple";
+
+ public static final String rangerUserName = "admin";
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ public static final String rangerPassword = "rangerR0cks!";
Review Comment:
The `rangerR0cks!` is the Ranger admin default password.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
Review Comment:
DONE
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy is not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilege -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilege))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role is not exist. */
+ private RangerRole createRangerRole(String roleName) {
Review Comment:
DONE
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
Review Comment:
Securable Object is very complex, So we didn't merge it.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy is not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilege -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilege))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role is not exist. */
Review Comment:
DONE
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1723284628
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
Review Comment:
Only return the policies that are delegate Gravitino management
```suggestion
// Only return the policies that are managed by Gravitino.
```
Comment
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#issuecomment-2301431331
@yuqi1129
> Policies can't be null, please see
>
> // Only return the policies that are managed by Gravitino.
> if (policies.size() > 1) {
> throw new AuthorizationPluginException(
> "Each metadata object only have one Gravitino management enable policies.");
> }
But policies cloud be equal to 1 or 0.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724555745
##########
authorizations/authorization-ranger/src/main/resources/META-INF/services/org.apache.gravitino.connector.authorization.AuthorizationProvider:
##########
@@ -0,0 +1,19 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+org.apache.gravitino.authorization.ranger.RangerAuthorization
Review Comment:
RangerAuthorization is abstract class. Is it ok to use it here?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724759506
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,583 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.authorization.ranger.reference.VXGroup;
+import org.apache.gravitino.authorization.ranger.reference.VXGroupList;
+import org.apache.gravitino.authorization.ranger.reference.VXUser;
+import org.apache.gravitino.authorization.ranger.reference.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Ranger authorization operations plugin abstract class. <br>
+ * 1. For Ranger limit, The same metadata object only has a unique Ranger policy, So a Ranger policy
+ * maybe contains multiple Gravitino securable objects. <br>
+ * 2. For easy management, each Ranger privilege will create one RangerPolicyItemAccess in the
+ * policy. <br>
+ * 3. Ranger also have Role concept, and support adds multiple users or groups in the Ranger Role,
+ * So we can use the Ranger Role to implement the Gravitino Role. <br>
+ * 4. The Ranger policy also supports multiple users and groups, But we only use a user or group to
+ * implement Gravitino Owner concept. <br>
+ */
+public class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected String rangerServiceName;
+ protected RangerClientExtend rangerClient;
+ private RangerHelper rangerHelper;
+ @VisibleForTesting public final String rangerAdminName;
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ rangerAdminName = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ RangerHelper.check(rangerUrl != null, "Ranger admin URL is required");
+ RangerHelper.check(authType != null, "Ranger auth type is required");
+ RangerHelper.check(rangerAdminName != null, "Ranger username is required");
+ RangerHelper.check(password != null, "Ranger password is required");
+ RangerHelper.check(rangerServiceName != null, "Ranger service name is required");
+ rangerClient = new RangerClientExtend(rangerUrl, authType, rangerAdminName, password);
+ rangerHelper = new RangerHelper(this, catalogProvider);
+ }
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return rangerHelper.privilegesMapping.get(name);
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(rangerHelper.ownerPrivileges);
+ }
+
+ /**
+ * Create a new role in the Ranger. <br>
+ * 1. Create a policy for metadata object. <br>
+ * 2. Save role name in the Policy items. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ return rangerHelper.checkRangerRole(role.name());
+ }
+
+ /** Remove the role name from the Ranger policy item, and delete this Role in the Ranger. <br> */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, delete the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), rangerAdminName, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult = doRemoveSecurableObject((RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult = doUpdateSecurableObject((RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ * 1. If the metadata object already has an owner, then transfer the ownership from preOwner to
+ * newOwner, The function params preOwner and newOwner don't equal null. <br>
+ * 2. If the metadata object doesn't have an owner, then set the owner to newOwner, The function
+ * params preOwner equal null and newOwner don't equal null. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object.
+ * @param newOwner The new owner of the metadata object.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ RangerHelper.check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = rangerHelper.findManagedPolicy(metadataObject);
+ try {
+ if (policy == null) {
+ policy = rangerHelper.addOwnerToNewPolicy(metadataObject, newOwner);
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerHelper.updatePolicyOwner(policy, preOwner, newOwner);
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this user to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param user The user to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role: {} to user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this user from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param user The user to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this group to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Grant role: {} to group: {} failed!", role, group, e);
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this group from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param group The group to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from group: {} failed!", role, group, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
Review Comment:
```suggestion
LOG.warn("The group({}) doesn't exist in the Ranger!", group);
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724878878
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHelper.java:
##########
@@ -0,0 +1,533 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This class is a helper class for the Ranger authorization plugin. It provides the ability to
+ * manage the Ranger policies and roles.
+ */
+public class RangerHelper {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerHelper.class);
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ RangerAuthorizationPlugin rangerAuthorizationPlugin;
+
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ /** The owner privileges, the owner can do anything on the metadata object */
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise search, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, If you use `db.table` condition to search policy, the Ranger will
+ * match `db1.table1`, `db1.table2`, `db*.table*`, So we need to manually precisely filter this
+ * research results. <br>
+ * policySearchKeys: The search Ranger policy condition key defines. <br>
+ * policyPreciseFilterKeys: The precise filter Ranger search results key defines <br>
+ */
+ protected List<String> policySearchKeys = null;
+
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public RangerHelper(RangerAuthorizationPlugin rangerAuthorizationPlugin, String catalogProvider) {
+ this.rangerAuthorizationPlugin = rangerAuthorizationPlugin;
+ switch (catalogProvider) {
+ case "hive":
+ initPrivilegesMapping();
+ initOwnerPrivileges();
+ initPolicySearchKeys();
+ initPreciseFilterKeys();
+ break;
+ default:
+ throw new IllegalArgumentException(
+ "Authorization plugin unsupported catalog provider: " + catalogProvider);
+ }
+ }
+
+ /** Initial mapping Gravitino privilege name to the underlying authorization system privileges. */
+ private void initPrivilegesMapping() {
+ privilegesMapping =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.MODIFY_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_UPDATE,
+ RangerDefines.ACCESS_TYPE_HIVE_ALTER,
+ RangerDefines.ACCESS_TYPE_HIVE_WRITE))
+ .put(
+ Privilege.Name.SELECT_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_READ, RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .build();
+ }
+
+ /** Initial Owner privileges */
+ private void initOwnerPrivileges() {
+ ownerPrivileges = ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_ALL);
+ }
+
+ /** Initial Ranger policy search key defines */
+ private void initPolicySearchKeys() {
+ policySearchKeys =
+ Arrays.asList(
+ RangerDefines.SEARCH_FILTER_DATABASE,
+ RangerDefines.SEARCH_FILTER_TABLE,
+ RangerDefines.SEARCH_FILTER_COLUMN);
+ }
+
+ /** Initial precise filter key defines */
+ private void initPreciseFilterKeys() {
+ policyPreciseFilterKeys =
+ Arrays.asList(
+ RangerDefines.RESOURCE_DATABASE,
+ RangerDefines.RESOURCE_TABLE,
+ RangerDefines.RESOURCE_COLUMN);
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Set<String> setAccesses = new HashSet<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (setAccesses.contains(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ setAccesses.add(access.getType());
+ });
+ }
+
+ /**
+ * Add policy item access items base the securable object's privileges. <br>
+ * We cannot clean the policy items because one Ranger policy maybe contains multiple Gravitino
+ * securable objects. <br>
+ */
+ void addPolicyItem(RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkPrivileges(securableObject);
+
+ // Add the policy items by the securable object's privileges
+ securableObject
+ .privileges()
+ .forEach(
+ gravitinoPrivilege -> {
+ // Translate the Gravitino privilege to map Ranger privilege
+ rangerAuthorizationPlugin
+ .translatePrivilege(gravitinoPrivilege.name())
+ .forEach(
+ mappedPrivilege -> {
+ // Find the policy item that matches Gravitino privilege
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItems =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ access -> access.getType().equals(mappedPrivilege));
+ })
+ .collect(Collectors.toList());
+
+ if (matchPolicyItems.size() == 0) {
+ // If the policy item does not exist, then create a new policy item
+ RangerPolicy.RangerPolicyItem policyItem =
+ new RangerPolicy.RangerPolicyItem();
+ RangerPolicy.RangerPolicyItemAccess access =
+ new RangerPolicy.RangerPolicyItemAccess();
+ access.setType(mappedPrivilege);
+ policyItem.getAccesses().add(access);
+ policyItem.getRoles().add(roleName);
+ if (Privilege.Condition.ALLOW == gravitinoPrivilege.condition()) {
+ policy.getPolicyItems().add(policyItem);
+ } else {
+ policy.getDenyPolicyItems().add(policyItem);
+ }
+ } else {
+ // If the policy item exists, then add the role to the policy item
+ matchPolicyItems.stream()
+ .forEach(
+ policyItem -> {
+ // If the role is not in the policy item, then add it
+ if (!policyItem.getRoles().contains(roleName)) {
+ policyItem.getRoles().add(roleName);
+ }
+ });
+ }
+ });
+ });
+ }
+
+ /**
+ * Remove policy item base the securable object's privileges and role name. <br>
+ * We cannot directly clean the policy items because one Ranger policy maybe contains multiple
+ * Gravitino privilege objects. <br>
+ */
+ void removePolicyItem(RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkPrivileges(securableObject);
+
+ // Delete the policy role base the securable object's privileges
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ boolean matchPrivilege =
+ securableObject.privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(
+ privilege ->
+ rangerAuthorizationPlugin
+ .translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .anyMatch(
+ privilege -> {
+ return access.getType().equals(privilege);
+ });
+ if (matchPrivilege
+ && !policyItem.getUsers().isEmpty()
+ && !policyItem.getGroups().isEmpty()) {
+ // Not ownership policy item, then remove the role
+ policyItem.getRoles().removeIf(roleName::equals);
+ }
+ });
+ });
+
+ // Delete the policy items if the roles are empty and not ownership policy item
+ policy
+ .getPolicyItems()
+ .removeIf(
+ policyItem -> {
+ return policyItem.getRoles().isEmpty()
+ && policyItem.getUsers().isEmpty()
+ && policyItem.getGroups().isEmpty();
+ });
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param securableObject The securable object to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ private boolean checkPrivileges(SecurableObject securableObject) {
+ securableObject
+ .privileges()
+ .forEach(
+ privilege -> {
+ check(
+ privilegesMapping.containsKey(privilege.name()),
+ "This privilege %s is not supported in the Ranger hive authorization",
+ privilege.name());
+ });
+ return true;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
Review Comment:
```suggestion
Map<String, String> searchFilters = new HashMap<>();
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724551608
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerClientExtend.java:
##########
@@ -0,0 +1,184 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.collect.ImmutableMap;
+import com.sun.jersey.api.client.GenericType;
+import com.sun.jersey.api.client.UniformInterfaceException;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Map;
+import javax.ws.rs.HttpMethod;
+import javax.ws.rs.core.Response;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.ranger.RangerClient;
+import org.apache.ranger.RangerServiceException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Apache Ranger client extension <br>
+ * The class extends the RangerClient class and provides additional methods to create, search and
+ * delete users and groups
+ */
+public class RangerClientExtend extends RangerClient {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerClientExtend.class);
+ private static final String URI_USER_BASE = "/service/xusers/users";
+ private static final String URI_USER_BY_ID = URI_USER_BASE + "/%d";
+ private static final String URI_GROUP_BASE = "/service/xusers/groups";
+ private static final String URI_GROUP_BY_ID = URI_GROUP_BASE + "/%d";
+ private static final String URI_CREATE_EXTERNAL_USER = URI_USER_BASE + "/external";
+
+ // Ranger user APIs
+ private static final API SEARCH_USER = new API(URI_USER_BASE, HttpMethod.GET, Response.Status.OK);
+ private static final API CREATE_EXTERNAL_USER =
+ new API(URI_CREATE_EXTERNAL_USER, HttpMethod.POST, Response.Status.OK);
+ private static final API DELETE_USER =
+ new API(URI_USER_BY_ID, HttpMethod.DELETE, Response.Status.NO_CONTENT);
+
+ // Ranger group APIs
+ private static final API CREATE_GROUP =
+ new API(URI_GROUP_BASE, HttpMethod.POST, Response.Status.OK);
+ private static final API SEARCH_GROUP =
+ new API(URI_GROUP_BASE, HttpMethod.GET, Response.Status.OK);
+ // private static final API GET_GROUP = new API(URI_GROUP_BY_ID, HttpMethod.GET,
+ // Response.Status.OK);
+ private static final API DELETE_GROUP =
+ new API(URI_GROUP_BY_ID, HttpMethod.DELETE, Response.Status.NO_CONTENT);
+
+ // apache/ranger/intg/src/main/java/org/apache/ranger/RangerClient.java
+ // The private method callAPI of Ranger is called by reflection
+ // private <T> T callAPI(API api, Map<String, String> params, Object request, GenericType<T>
+ // responseType) throws RangerServiceException
+ private Method callAPIMethodGenericResponseType;
+
+ // private <T> T callAPI(API api, Map<String, String> params, Object request, Class<T>
+ // responseType) throws RangerServiceException
+ private Method callAPIMethodClassResponseType;
+ // private void callAPI(API api, Map<String, String> params) throws RangerServiceException
+ private Method callAPIMethodNonResponse;
+
+ public RangerClientExtend(String hostName, String authType, String username, String password) {
+ super(hostName, authType, username, password, null);
+
+ // initialize callAPI method
+ try {
+ callAPIMethodGenericResponseType =
+ RangerClient.class.getDeclaredMethod(
+ "callAPI", API.class, Map.class, Object.class, GenericType.class);
+ callAPIMethodGenericResponseType.setAccessible(true);
+
+ callAPIMethodNonResponse =
+ RangerClient.class.getDeclaredMethod("callAPI", API.class, Map.class);
+ callAPIMethodNonResponse.setAccessible(true);
+
+ callAPIMethodClassResponseType =
+ RangerClient.class.getDeclaredMethod(
+ "callAPI", API.class, Map.class, Object.class, Class.class);
+ callAPIMethodClassResponseType.setAccessible(true);
+ } catch (NoSuchMethodException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public Boolean createUser(VXUser user) throws RuntimeException {
+ try {
+ callAPIMethodClassResponseType.invoke(this, CREATE_EXTERNAL_USER, null, user, VXUser.class);
+ } catch (UniformInterfaceException e) {
+ LOG.error("Failed to create user: " + e.getResponse().getEntity(String.class));
+ return Boolean.FALSE;
+ } catch (InvocationTargetException | IllegalAccessException e) {
+ Throwable cause = e.getCause();
+ if (cause instanceof com.sun.jersey.api.client.UniformInterfaceException) {
+ com.sun.jersey.api.client.UniformInterfaceException uniformException =
+ (com.sun.jersey.api.client.UniformInterfaceException) cause;
+ int statusCode = uniformException.getResponse().getStatus();
+ if (statusCode == 204) {
+ // Because Ranger use asynchronous create user, so the response status is 204, research
+ // the user to check if it is created
+ VXUserList userList = searchUser(ImmutableMap.of("name", user.getName()));
Review Comment:
User API return a precise name or a fuzzy name list?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724660447
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have a Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contains multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manually precisely filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are managed by Gravitino.
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ mapAccesses.put(access.getType(), true);
+ });
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy exists but has different privileges, also return true. Because one Ranger
+ * policy maybe contain multiple Gravitino securable object <br>
+ * 4. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravitino securable object's privilege
+ // and roleName
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If it exists policy with the same privilege, then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(change.getSecurableObject().fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(
+ SecurableObjects.DOT_SPLITTER.splitToList(change.getSecurableObject().fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ List<String> rangerDefinesList =
+ Lists.newArrayList(
+ RangerDefines.RESOURCE_DATABASE,
+ RangerDefines.RESOURCE_TABLE,
+ RangerDefines.RESOURCE_COLUMN);
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy.getResources().put(rangerDefinesList.get(i), policyResource);
+ }
+ }
+
+ addPolicyItem(policy, change.getRoleName(), change.getSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return true;
+ }
+
+ /**
+ * Remove the securable object's privilege from the policy. <br>
+ * Because Ranger uses unique metadata to location Ranger policy and manages all the privileges,
+ * So A Ranger policy maybe contains multiple Gravitino privilege objects. <br>
+ * Remove Ranger policy item condition is: <br>
+ * 1. This Ranger policy item's accesses are equal the Gravitino securable object's privilege.
+ * <br>
+ * 2. This Ranger policy item's users and groups are empty. <br>
+ * If policy didn't have any policy item, then delete this policy: <br>
+ */
+ private boolean doRemoveSecurableObject(
Review Comment:
The logic is too different
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerClientExtend.java:
##########
@@ -0,0 +1,184 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.collect.ImmutableMap;
+import com.sun.jersey.api.client.GenericType;
+import com.sun.jersey.api.client.UniformInterfaceException;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Map;
+import javax.ws.rs.HttpMethod;
+import javax.ws.rs.core.Response;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.ranger.RangerClient;
+import org.apache.ranger.RangerServiceException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Apache Ranger client extension <br>
+ * The class extends the RangerClient class and provides additional methods to create, search and
+ * delete users and groups
+ */
+public class RangerClientExtend extends RangerClient {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerClientExtend.class);
+ private static final String URI_USER_BASE = "/service/xusers/users";
+ private static final String URI_USER_BY_ID = URI_USER_BASE + "/%d";
+ private static final String URI_GROUP_BASE = "/service/xusers/groups";
+ private static final String URI_GROUP_BY_ID = URI_GROUP_BASE + "/%d";
+ private static final String URI_CREATE_EXTERNAL_USER = URI_USER_BASE + "/external";
+
+ // Ranger user APIs
+ private static final API SEARCH_USER = new API(URI_USER_BASE, HttpMethod.GET, Response.Status.OK);
+ private static final API CREATE_EXTERNAL_USER =
+ new API(URI_CREATE_EXTERNAL_USER, HttpMethod.POST, Response.Status.OK);
+ private static final API DELETE_USER =
+ new API(URI_USER_BY_ID, HttpMethod.DELETE, Response.Status.NO_CONTENT);
+
+ // Ranger group APIs
+ private static final API CREATE_GROUP =
+ new API(URI_GROUP_BASE, HttpMethod.POST, Response.Status.OK);
+ private static final API SEARCH_GROUP =
+ new API(URI_GROUP_BASE, HttpMethod.GET, Response.Status.OK);
+ // private static final API GET_GROUP = new API(URI_GROUP_BY_ID, HttpMethod.GET,
+ // Response.Status.OK);
+ private static final API DELETE_GROUP =
+ new API(URI_GROUP_BY_ID, HttpMethod.DELETE, Response.Status.NO_CONTENT);
+
+ // apache/ranger/intg/src/main/java/org/apache/ranger/RangerClient.java
+ // The private method callAPI of Ranger is called by reflection
+ // private <T> T callAPI(API api, Map<String, String> params, Object request, GenericType<T>
+ // responseType) throws RangerServiceException
+ private Method callAPIMethodGenericResponseType;
+
+ // private <T> T callAPI(API api, Map<String, String> params, Object request, Class<T>
+ // responseType) throws RangerServiceException
+ private Method callAPIMethodClassResponseType;
+ // private void callAPI(API api, Map<String, String> params) throws RangerServiceException
+ private Method callAPIMethodNonResponse;
+
+ public RangerClientExtend(String hostName, String authType, String username, String password) {
+ super(hostName, authType, username, password, null);
+
+ // initialize callAPI method
+ try {
+ callAPIMethodGenericResponseType =
+ RangerClient.class.getDeclaredMethod(
+ "callAPI", API.class, Map.class, Object.class, GenericType.class);
+ callAPIMethodGenericResponseType.setAccessible(true);
+
+ callAPIMethodNonResponse =
+ RangerClient.class.getDeclaredMethod("callAPI", API.class, Map.class);
+ callAPIMethodNonResponse.setAccessible(true);
+
+ callAPIMethodClassResponseType =
+ RangerClient.class.getDeclaredMethod(
+ "callAPI", API.class, Map.class, Object.class, Class.class);
+ callAPIMethodClassResponseType.setAccessible(true);
+ } catch (NoSuchMethodException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public Boolean createUser(VXUser user) throws RuntimeException {
+ try {
+ callAPIMethodClassResponseType.invoke(this, CREATE_EXTERNAL_USER, null, user, VXUser.class);
+ } catch (UniformInterfaceException e) {
+ LOG.error("Failed to create user: " + e.getResponse().getEntity(String.class));
+ return Boolean.FALSE;
+ } catch (InvocationTargetException | IllegalAccessException e) {
+ Throwable cause = e.getCause();
+ if (cause instanceof com.sun.jersey.api.client.UniformInterfaceException) {
+ com.sun.jersey.api.client.UniformInterfaceException uniformException =
+ (com.sun.jersey.api.client.UniformInterfaceException) cause;
+ int statusCode = uniformException.getResponse().getStatus();
+ if (statusCode == 204) {
+ // Because Ranger use asynchronous create user, so the response status is 204, research
+ // the user to check if it is created
+ VXUserList userList = searchUser(ImmutableMap.of("name", user.getName()));
Review Comment:
YES
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerClientExtend.java:
##########
@@ -0,0 +1,184 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.collect.ImmutableMap;
+import com.sun.jersey.api.client.GenericType;
+import com.sun.jersey.api.client.UniformInterfaceException;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Map;
+import javax.ws.rs.HttpMethod;
+import javax.ws.rs.core.Response;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.ranger.RangerClient;
+import org.apache.ranger.RangerServiceException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Apache Ranger client extension <br>
+ * The class extends the RangerClient class and provides additional methods to create, search and
+ * delete users and groups
+ */
+public class RangerClientExtend extends RangerClient {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerClientExtend.class);
+ private static final String URI_USER_BASE = "/service/xusers/users";
+ private static final String URI_USER_BY_ID = URI_USER_BASE + "/%d";
+ private static final String URI_GROUP_BASE = "/service/xusers/groups";
+ private static final String URI_GROUP_BY_ID = URI_GROUP_BASE + "/%d";
+ private static final String URI_CREATE_EXTERNAL_USER = URI_USER_BASE + "/external";
+
+ // Ranger user APIs
+ private static final API SEARCH_USER = new API(URI_USER_BASE, HttpMethod.GET, Response.Status.OK);
+ private static final API CREATE_EXTERNAL_USER =
+ new API(URI_CREATE_EXTERNAL_USER, HttpMethod.POST, Response.Status.OK);
+ private static final API DELETE_USER =
+ new API(URI_USER_BY_ID, HttpMethod.DELETE, Response.Status.NO_CONTENT);
+
+ // Ranger group APIs
+ private static final API CREATE_GROUP =
+ new API(URI_GROUP_BASE, HttpMethod.POST, Response.Status.OK);
+ private static final API SEARCH_GROUP =
+ new API(URI_GROUP_BASE, HttpMethod.GET, Response.Status.OK);
+ // private static final API GET_GROUP = new API(URI_GROUP_BY_ID, HttpMethod.GET,
Review Comment:
DONE
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
Review Comment:
DONE
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have a Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contains multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
Review Comment:
I rewrited these comments.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,998 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have a Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
Review Comment:
I already updated `onRoleAcquired()` function.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,998 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have a Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
Review Comment:
Yes, I split some code to RangerHelper.java
##########
authorizations/authorization-ranger/src/main/resources/META-INF/services/org.apache.gravitino.connector.authorization.AuthorizationProvider:
##########
@@ -0,0 +1,19 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+org.apache.gravitino.authorization.ranger.RangerAuthorization
Review Comment:
I already change RangerAuthorization to an entity class
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,998 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have a Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contains multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Grant role: {} to group: {} failed!", role, group, e);
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from group: {} failed!", role, group, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
Review Comment:
DONE
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,998 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have a Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contains multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Grant role: {} to group: {} failed!", role, group, e);
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from group: {} failed!", role, group, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users =
+ StringUtils.isEmpty(userName) ? Sets.newHashSet() : Sets.newHashSet(userName);
+ Set<String> groups =
+ StringUtils.isEmpty(groupName) ? Sets.newHashSet() : Sets.newHashSet(groupName);
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(Sets.newHashSet(roleName));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception, if the role does not exist, we will then create it.
+ LOG.warn("The role({}) is not exist in the Ranger!", roleName);
+ }
+
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manually precisely filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are managed by Gravitino.
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
Review Comment:
DONE
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,998 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have a Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
Review Comment:
DONE
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1721883659
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHiveAuthorizationPlugin.java:
##########
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Set;
+import org.apache.gravitino.authorization.Privilege;
+
+/**
+ * RangerHiveAuthorizationPlugin is a plugin for Apache Ranger to manage the Hive authorization of
+ * the Apache Gravitino.
+ */
+public class RangerHiveAuthorizationPlugin extends RangerAuthorizationPlugin {
+ public RangerHiveAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super(catalogProvider, config);
+ }
+
+ /**
+ * Ranger hive's privilege have `select`, `update`, `create`, `drop`, `alter`, `index`, `lock`,
+ * `read`, `write`, `repladmin`, `serviceadmin`, `refresh` and `all`. Reference:
+ * ranger/agents-common/src/main/resources/service-defs/ranger-servicedef-hive.json
+ */
+ @Override
+ protected void initMapPrivileges() {
+ mapPrivileges =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
Review Comment:
These are two scenarios here:
1. If you have SecurableObjects('catalog.schema.*', CREATE_TABLE), this permission mean is you can create any table under the `catalog.schema`.
2. If you have SecurableObjects('catalog.schema.tab1', CREATE_TABLE), this permission mean is you can create table `tab1` on the `catalog.schema`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1723220083
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
Review Comment:
Could you add more comments for this method?
What's the policy? What fields does it have? How to mapping it from securable object?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1723258341
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ mapAccesses.put(access.getType(), true);
+ });
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy exists but has different privileges, also return true. Because one Ranger
+ * policy maybe contain multiple Gravitino securable object <br>
+ * 4. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravition securable object's privilege
+ // and roleName
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If exist policy and have same privilege then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(change.getSecurableObject().fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(
+ SecurableObjects.DOT_SPLITTER.splitToList(change.getSecurableObject().fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
Review Comment:
You can wrap `RangerDefines.RESOURCE_DATABASE`, `RangerDefines.RESOURCE_TABLE` and `RangerDefines.RESOURCE_COLUMN` to a list.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1723280170
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
Review Comment:
```suggestion
* Because one Ranger policy maybe contains multiple Gravitino securable objects, <br>
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724471028
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerClientExtend.java:
##########
@@ -0,0 +1,184 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.collect.ImmutableMap;
+import com.sun.jersey.api.client.GenericType;
+import com.sun.jersey.api.client.UniformInterfaceException;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Map;
+import javax.ws.rs.HttpMethod;
+import javax.ws.rs.core.Response;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.ranger.RangerClient;
+import org.apache.ranger.RangerServiceException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Apache Ranger client extension <br>
+ * The class extends the RangerClient class and provides additional methods to create, search and
+ * delete users and groups
+ */
+public class RangerClientExtend extends RangerClient {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerClientExtend.class);
+ private static final String URI_USER_BASE = "/service/xusers/users";
+ private static final String URI_USER_BY_ID = URI_USER_BASE + "/%d";
+ private static final String URI_GROUP_BASE = "/service/xusers/groups";
+ private static final String URI_GROUP_BY_ID = URI_GROUP_BASE + "/%d";
+ private static final String URI_CREATE_EXTERNAL_USER = URI_USER_BASE + "/external";
+
+ // Ranger user APIs
+ private static final API SEARCH_USER = new API(URI_USER_BASE, HttpMethod.GET, Response.Status.OK);
+ private static final API CREATE_EXTERNAL_USER =
+ new API(URI_CREATE_EXTERNAL_USER, HttpMethod.POST, Response.Status.OK);
+ private static final API DELETE_USER =
+ new API(URI_USER_BY_ID, HttpMethod.DELETE, Response.Status.NO_CONTENT);
+
+ // Ranger group APIs
+ private static final API CREATE_GROUP =
+ new API(URI_GROUP_BASE, HttpMethod.POST, Response.Status.OK);
+ private static final API SEARCH_GROUP =
+ new API(URI_GROUP_BASE, HttpMethod.GET, Response.Status.OK);
+ // private static final API GET_GROUP = new API(URI_GROUP_BY_ID, HttpMethod.GET,
Review Comment:
Do we need remove unused comment?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724773530
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
Review Comment:
@xunliu Could you reply this?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724906342
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHelper.java:
##########
@@ -0,0 +1,533 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This class is a helper class for the Ranger authorization plugin. It provides the ability to
+ * manage the Ranger policies and roles.
+ */
+public class RangerHelper {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerHelper.class);
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ RangerAuthorizationPlugin rangerAuthorizationPlugin;
+
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ /** The owner privileges, the owner can do anything on the metadata object */
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise search, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, If you use `db.table` condition to search policy, the Ranger will
+ * match `db1.table1`, `db1.table2`, `db*.table*`, So we need to manually precisely filter this
+ * research results. <br>
+ * policySearchKeys: The search Ranger policy condition key defines. <br>
+ * policyPreciseFilterKeys: The precise filter Ranger search results key defines <br>
+ */
+ protected List<String> policySearchKeys = null;
+
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public RangerHelper(RangerAuthorizationPlugin rangerAuthorizationPlugin, String catalogProvider) {
+ this.rangerAuthorizationPlugin = rangerAuthorizationPlugin;
+ switch (catalogProvider) {
+ case "hive":
+ initPrivilegesMapping();
+ initOwnerPrivileges();
+ initPolicySearchKeys();
+ initPreciseFilterKeys();
+ break;
+ default:
+ throw new IllegalArgumentException(
+ "Authorization plugin unsupported catalog provider: " + catalogProvider);
+ }
+ }
+
+ /** Initial mapping Gravitino privilege name to the underlying authorization system privileges. */
+ private void initPrivilegesMapping() {
+ privilegesMapping =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.MODIFY_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_UPDATE,
+ RangerDefines.ACCESS_TYPE_HIVE_ALTER,
+ RangerDefines.ACCESS_TYPE_HIVE_WRITE))
+ .put(
+ Privilege.Name.SELECT_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_READ, RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .build();
+ }
+
+ /** Initial Owner privileges */
+ private void initOwnerPrivileges() {
+ ownerPrivileges = ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_ALL);
+ }
+
+ /** Initial Ranger policy search key defines */
+ private void initPolicySearchKeys() {
+ policySearchKeys =
+ Arrays.asList(
+ RangerDefines.SEARCH_FILTER_DATABASE,
+ RangerDefines.SEARCH_FILTER_TABLE,
+ RangerDefines.SEARCH_FILTER_COLUMN);
+ }
+
+ /** Initial precise filter key defines */
+ private void initPreciseFilterKeys() {
+ policyPreciseFilterKeys =
+ Arrays.asList(
+ RangerDefines.RESOURCE_DATABASE,
+ RangerDefines.RESOURCE_TABLE,
+ RangerDefines.RESOURCE_COLUMN);
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Set<String> setAccesses = new HashSet<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (setAccesses.contains(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ setAccesses.add(access.getType());
+ });
+ }
+
+ /**
+ * Add policy item access items base the securable object's privileges. <br>
+ * We cannot clean the policy items because one Ranger policy maybe contains multiple Gravitino
+ * securable objects. <br>
+ */
+ void addPolicyItem(RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkPrivileges(securableObject);
+
+ // Add the policy items by the securable object's privileges
+ securableObject
+ .privileges()
+ .forEach(
+ gravitinoPrivilege -> {
+ // Translate the Gravitino privilege to map Ranger privilege
+ rangerAuthorizationPlugin
+ .translatePrivilege(gravitinoPrivilege.name())
+ .forEach(
+ mappedPrivilege -> {
+ // Find the policy item that matches Gravitino privilege
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItems =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ access -> access.getType().equals(mappedPrivilege));
+ })
+ .collect(Collectors.toList());
+
+ if (matchPolicyItems.size() == 0) {
+ // If the policy item does not exist, then create a new policy item
+ RangerPolicy.RangerPolicyItem policyItem =
+ new RangerPolicy.RangerPolicyItem();
+ RangerPolicy.RangerPolicyItemAccess access =
+ new RangerPolicy.RangerPolicyItemAccess();
+ access.setType(mappedPrivilege);
+ policyItem.getAccesses().add(access);
+ policyItem.getRoles().add(roleName);
+ if (Privilege.Condition.ALLOW == gravitinoPrivilege.condition()) {
+ policy.getPolicyItems().add(policyItem);
+ } else {
+ policy.getDenyPolicyItems().add(policyItem);
+ }
+ } else {
+ // If the policy item exists, then add the role to the policy item
+ matchPolicyItems.stream()
+ .forEach(
+ policyItem -> {
+ // If the role is not in the policy item, then add it
+ if (!policyItem.getRoles().contains(roleName)) {
+ policyItem.getRoles().add(roleName);
+ }
+ });
+ }
+ });
+ });
+ }
+
+ /**
+ * Remove policy item base the securable object's privileges and role name. <br>
+ * We cannot directly clean the policy items because one Ranger policy maybe contains multiple
+ * Gravitino privilege objects. <br>
+ */
+ void removePolicyItem(RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkPrivileges(securableObject);
+
+ // Delete the policy role base the securable object's privileges
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ boolean matchPrivilege =
+ securableObject.privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(
+ privilege ->
+ rangerAuthorizationPlugin
+ .translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .anyMatch(
+ privilege -> {
+ return access.getType().equals(privilege);
+ });
+ if (matchPrivilege
+ && !policyItem.getUsers().isEmpty()
+ && !policyItem.getGroups().isEmpty()) {
+ // Not ownership policy item, then remove the role
+ policyItem.getRoles().removeIf(roleName::equals);
+ }
+ });
+ });
+
+ // Delete the policy items if the roles are empty and not ownership policy item
+ policy
+ .getPolicyItems()
+ .removeIf(
+ policyItem -> {
+ return policyItem.getRoles().isEmpty()
+ && policyItem.getUsers().isEmpty()
+ && policyItem.getGroups().isEmpty();
+ });
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param securableObject The securable object to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ private boolean checkPrivileges(SecurableObject securableObject) {
+ securableObject
+ .privileges()
+ .forEach(
+ privilege -> {
+ check(
+ privilegesMapping.containsKey(privilege.name()),
+ "This privilege %s is not supported in the Ranger hive authorization",
+ privilege.name());
+ });
+ return true;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(
+ RangerDefines.SEARCH_FILTER_SERVICE_NAME, rangerAuthorizationPlugin.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policySearchKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies =
+ rangerAuthorizationPlugin.rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ /**
+ * Because Ranger doesn't support the precise search, Ranger will return the policy meets
+ * the wildcard(*,?) conditions, If you use `db.table` condition to search policy, the
+ * Ranger will match `db1.table1`, `db1.table2`, `db*.table*`, So we need to manually
+ * precisely filter this research results.
+ */
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are managed by Gravitino.
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
Review Comment:
I and @yuqi prefer
```
if (policies.isEmpty()) {
return null;
}
policy = policies.get(0);
policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
````
It's more readable.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724485563
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy is not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilege -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilege))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role is not exist. */
+ private RangerRole createRangerRole(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role is not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
Review Comment:
Policies can't be null, please see
```
// Only return the policies that are managed by Gravitino.
if (policies.size() > 1) {
throw new AuthorizationPluginException(
"Each metadata object only have one Gravitino management enable policies.");
}
```
##########
api/src/main/java/org/apache/gravitino/authorization/RoleChange.java:
##########
@@ -149,7 +189,101 @@ public int hashCode() {
*/
@Override
public String toString() {
- return "REMOVESECURABLEOBJECT " + securableObject;
+ return "REMOVESECURABLEOBJECT " + roleName + " " + securableObject;
+ }
+ }
+
+ /**
+ * A UpdateSecurableObject is to update securable object's privilege from role. <br>
+ * The securable object's metadata entity must be the same as new securable object's metadata
+ * entity. <br>
+ * The securable object's privilege must be different as new securable object's privilege. <br>
Review Comment:
...must be different from...
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
Review Comment:
Whether this privilege is supported by the underlying permission system.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724747227
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerClientExtend.java:
##########
@@ -0,0 +1,184 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.collect.ImmutableMap;
+import com.sun.jersey.api.client.GenericType;
+import com.sun.jersey.api.client.UniformInterfaceException;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Map;
+import javax.ws.rs.HttpMethod;
+import javax.ws.rs.core.Response;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.ranger.RangerClient;
+import org.apache.ranger.RangerServiceException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Apache Ranger client extension <br>
+ * The class extends the RangerClient class and provides additional methods to create, search and
+ * delete users and groups
+ */
+public class RangerClientExtend extends RangerClient {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerClientExtend.class);
+ private static final String URI_USER_BASE = "/service/xusers/users";
+ private static final String URI_USER_BY_ID = URI_USER_BASE + "/%d";
+ private static final String URI_GROUP_BASE = "/service/xusers/groups";
+ private static final String URI_GROUP_BY_ID = URI_GROUP_BASE + "/%d";
+ private static final String URI_CREATE_EXTERNAL_USER = URI_USER_BASE + "/external";
+
+ // Ranger user APIs
+ private static final API SEARCH_USER = new API(URI_USER_BASE, HttpMethod.GET, Response.Status.OK);
+ private static final API CREATE_EXTERNAL_USER =
+ new API(URI_CREATE_EXTERNAL_USER, HttpMethod.POST, Response.Status.OK);
+ private static final API DELETE_USER =
+ new API(URI_USER_BY_ID, HttpMethod.DELETE, Response.Status.NO_CONTENT);
+
+ // Ranger group APIs
+ private static final API CREATE_GROUP =
+ new API(URI_GROUP_BASE, HttpMethod.POST, Response.Status.OK);
+ private static final API SEARCH_GROUP =
+ new API(URI_GROUP_BASE, HttpMethod.GET, Response.Status.OK);
+ // private static final API GET_GROUP = new API(URI_GROUP_BY_ID, HttpMethod.GET,
+ // Response.Status.OK);
+ private static final API DELETE_GROUP =
+ new API(URI_GROUP_BY_ID, HttpMethod.DELETE, Response.Status.NO_CONTENT);
+
+ // apache/ranger/intg/src/main/java/org/apache/ranger/RangerClient.java
+ // The private method callAPI of Ranger is called by reflection
+ // private <T> T callAPI(API api, Map<String, String> params, Object request, GenericType<T>
+ // responseType) throws RangerServiceException
+ private Method callAPIMethodGenericResponseType;
+
+ // private <T> T callAPI(API api, Map<String, String> params, Object request, Class<T>
+ // responseType) throws RangerServiceException
+ private Method callAPIMethodClassResponseType;
+ // private void callAPI(API api, Map<String, String> params) throws RangerServiceException
+ private Method callAPIMethodNonResponse;
+
+ public RangerClientExtend(String hostName, String authType, String username, String password) {
+ super(hostName, authType, username, password, null);
+
+ // initialize callAPI method
+ try {
+ callAPIMethodGenericResponseType =
+ RangerClient.class.getDeclaredMethod(
+ "callAPI", API.class, Map.class, Object.class, GenericType.class);
+ callAPIMethodGenericResponseType.setAccessible(true);
+
+ callAPIMethodNonResponse =
+ RangerClient.class.getDeclaredMethod("callAPI", API.class, Map.class);
+ callAPIMethodNonResponse.setAccessible(true);
+
+ callAPIMethodClassResponseType =
+ RangerClient.class.getDeclaredMethod(
+ "callAPI", API.class, Map.class, Object.class, Class.class);
+ callAPIMethodClassResponseType.setAccessible(true);
+ } catch (NoSuchMethodException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public Boolean createUser(VXUser user) throws RuntimeException {
+ try {
+ callAPIMethodClassResponseType.invoke(this, CREATE_EXTERNAL_USER, null, user, VXUser.class);
+ } catch (UniformInterfaceException e) {
+ LOG.error("Failed to create user: " + e.getResponse().getEntity(String.class));
+ return Boolean.FALSE;
+ } catch (InvocationTargetException | IllegalAccessException e) {
+ Throwable cause = e.getCause();
+ if (cause instanceof com.sun.jersey.api.client.UniformInterfaceException) {
+ com.sun.jersey.api.client.UniformInterfaceException uniformException =
+ (com.sun.jersey.api.client.UniformInterfaceException) cause;
+ int statusCode = uniformException.getResponse().getStatus();
+ if (statusCode == 204) {
+ // Because Ranger use asynchronous create user, so the response status is 204, research
+ // the user to check if it is created
+ VXUserList userList = searchUser(ImmutableMap.of("name", user.getName()));
Review Comment:
a precise name or a fuzzy name list?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724906342
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHelper.java:
##########
@@ -0,0 +1,533 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This class is a helper class for the Ranger authorization plugin. It provides the ability to
+ * manage the Ranger policies and roles.
+ */
+public class RangerHelper {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerHelper.class);
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ RangerAuthorizationPlugin rangerAuthorizationPlugin;
+
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ /** The owner privileges, the owner can do anything on the metadata object */
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise search, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, If you use `db.table` condition to search policy, the Ranger will
+ * match `db1.table1`, `db1.table2`, `db*.table*`, So we need to manually precisely filter this
+ * research results. <br>
+ * policySearchKeys: The search Ranger policy condition key defines. <br>
+ * policyPreciseFilterKeys: The precise filter Ranger search results key defines <br>
+ */
+ protected List<String> policySearchKeys = null;
+
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public RangerHelper(RangerAuthorizationPlugin rangerAuthorizationPlugin, String catalogProvider) {
+ this.rangerAuthorizationPlugin = rangerAuthorizationPlugin;
+ switch (catalogProvider) {
+ case "hive":
+ initPrivilegesMapping();
+ initOwnerPrivileges();
+ initPolicySearchKeys();
+ initPreciseFilterKeys();
+ break;
+ default:
+ throw new IllegalArgumentException(
+ "Authorization plugin unsupported catalog provider: " + catalogProvider);
+ }
+ }
+
+ /** Initial mapping Gravitino privilege name to the underlying authorization system privileges. */
+ private void initPrivilegesMapping() {
+ privilegesMapping =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.MODIFY_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_UPDATE,
+ RangerDefines.ACCESS_TYPE_HIVE_ALTER,
+ RangerDefines.ACCESS_TYPE_HIVE_WRITE))
+ .put(
+ Privilege.Name.SELECT_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_READ, RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .build();
+ }
+
+ /** Initial Owner privileges */
+ private void initOwnerPrivileges() {
+ ownerPrivileges = ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_ALL);
+ }
+
+ /** Initial Ranger policy search key defines */
+ private void initPolicySearchKeys() {
+ policySearchKeys =
+ Arrays.asList(
+ RangerDefines.SEARCH_FILTER_DATABASE,
+ RangerDefines.SEARCH_FILTER_TABLE,
+ RangerDefines.SEARCH_FILTER_COLUMN);
+ }
+
+ /** Initial precise filter key defines */
+ private void initPreciseFilterKeys() {
+ policyPreciseFilterKeys =
+ Arrays.asList(
+ RangerDefines.RESOURCE_DATABASE,
+ RangerDefines.RESOURCE_TABLE,
+ RangerDefines.RESOURCE_COLUMN);
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Set<String> setAccesses = new HashSet<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (setAccesses.contains(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ setAccesses.add(access.getType());
+ });
+ }
+
+ /**
+ * Add policy item access items base the securable object's privileges. <br>
+ * We cannot clean the policy items because one Ranger policy maybe contains multiple Gravitino
+ * securable objects. <br>
+ */
+ void addPolicyItem(RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkPrivileges(securableObject);
+
+ // Add the policy items by the securable object's privileges
+ securableObject
+ .privileges()
+ .forEach(
+ gravitinoPrivilege -> {
+ // Translate the Gravitino privilege to map Ranger privilege
+ rangerAuthorizationPlugin
+ .translatePrivilege(gravitinoPrivilege.name())
+ .forEach(
+ mappedPrivilege -> {
+ // Find the policy item that matches Gravitino privilege
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItems =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ access -> access.getType().equals(mappedPrivilege));
+ })
+ .collect(Collectors.toList());
+
+ if (matchPolicyItems.size() == 0) {
+ // If the policy item does not exist, then create a new policy item
+ RangerPolicy.RangerPolicyItem policyItem =
+ new RangerPolicy.RangerPolicyItem();
+ RangerPolicy.RangerPolicyItemAccess access =
+ new RangerPolicy.RangerPolicyItemAccess();
+ access.setType(mappedPrivilege);
+ policyItem.getAccesses().add(access);
+ policyItem.getRoles().add(roleName);
+ if (Privilege.Condition.ALLOW == gravitinoPrivilege.condition()) {
+ policy.getPolicyItems().add(policyItem);
+ } else {
+ policy.getDenyPolicyItems().add(policyItem);
+ }
+ } else {
+ // If the policy item exists, then add the role to the policy item
+ matchPolicyItems.stream()
+ .forEach(
+ policyItem -> {
+ // If the role is not in the policy item, then add it
+ if (!policyItem.getRoles().contains(roleName)) {
+ policyItem.getRoles().add(roleName);
+ }
+ });
+ }
+ });
+ });
+ }
+
+ /**
+ * Remove policy item base the securable object's privileges and role name. <br>
+ * We cannot directly clean the policy items because one Ranger policy maybe contains multiple
+ * Gravitino privilege objects. <br>
+ */
+ void removePolicyItem(RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkPrivileges(securableObject);
+
+ // Delete the policy role base the securable object's privileges
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ boolean matchPrivilege =
+ securableObject.privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(
+ privilege ->
+ rangerAuthorizationPlugin
+ .translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .anyMatch(
+ privilege -> {
+ return access.getType().equals(privilege);
+ });
+ if (matchPrivilege
+ && !policyItem.getUsers().isEmpty()
+ && !policyItem.getGroups().isEmpty()) {
+ // Not ownership policy item, then remove the role
+ policyItem.getRoles().removeIf(roleName::equals);
+ }
+ });
+ });
+
+ // Delete the policy items if the roles are empty and not ownership policy item
+ policy
+ .getPolicyItems()
+ .removeIf(
+ policyItem -> {
+ return policyItem.getRoles().isEmpty()
+ && policyItem.getUsers().isEmpty()
+ && policyItem.getGroups().isEmpty();
+ });
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param securableObject The securable object to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ private boolean checkPrivileges(SecurableObject securableObject) {
+ securableObject
+ .privileges()
+ .forEach(
+ privilege -> {
+ check(
+ privilegesMapping.containsKey(privilege.name()),
+ "This privilege %s is not supported in the Ranger hive authorization",
+ privilege.name());
+ });
+ return true;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(
+ RangerDefines.SEARCH_FILTER_SERVICE_NAME, rangerAuthorizationPlugin.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policySearchKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies =
+ rangerAuthorizationPlugin.rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ /**
+ * Because Ranger doesn't support the precise search, Ranger will return the policy meets
+ * the wildcard(*,?) conditions, If you use `db.table` condition to search policy, the
+ * Ranger will match `db1.table1`, `db1.table2`, `db*.table*`, So we need to manually
+ * precisely filter this research results.
+ */
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are managed by Gravitino.
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
Review Comment:
I and @yuqi prefer
```
if (policies.isEmpty()) {
return null;
}
RangerPolicy policy = policies.get(0);
policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
````
It's more readable.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "lw-yang (via GitHub)" <gi...@apache.org>.
lw-yang commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1716897327
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,179 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationHookException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.util.SearchFilter;
+
+/** Ranger authorization operations hooks interfaces. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+
+ /**
+ * Because UserGroupAuthorizationPlugin::onOwnerSet() interface function didn't have param Role,
+ * So we need predefine a role name
+ */
+ public static final String OWNER_ROLE_NAME = "OWNER";
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+ public static final String POLICY_ITEM_OWNER_USER = "{OWNER}";
+
+ public RangerAuthorizationPlugin() {
+ initMapPrivileges();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /** Whether this privilege is underlying permission system supported */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected static void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationHookException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public String formatPolicyName(String roleName, String securableObjectFullName) {
+ return roleName + "-" + securableObjectFullName;
Review Comment:
Why does policyName need to include role information? I think it's enough to use `securableObjectFullName`
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHiveAuthorizationPlugin.java:
##########
@@ -0,0 +1,840 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Privileges;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * RangerHiveAuthorizationPlugin is a plugin for Apache Ranger to manage the Hive authorization of
+ * the Apache Gravitino.
+ */
+public class RangerHiveAuthorizationPlugin extends RangerAuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerHiveAuthorizationPlugin.class);
+
+ public RangerHiveAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+ }
+
+ /**
+ * Ranger hive's privilege have `select`, `update`, `create`, `drop`, `alter`, `index`, `lock`,
+ * `read`, `write`, `repladmin`, `serviceadmin`, `refresh` and `all`.
+ *
+ * <p>Reference: ranger/agents-common/src/main/resources/service-defs/ranger-servicedef-hive.json
+ */
+ @Override
+ protected void initMapPrivileges() {
+ mapPrivileges =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(Privilege.Name.CREATE_SCHEMA, ImmutableSet.of("create"))
+ .put(Privilege.Name.CREATE_TABLE, ImmutableSet.of("create"))
+ .put(Privilege.Name.MODIFY_TABLE, ImmutableSet.of("update", "drop", "alter", "write"))
+ .put(Privilege.Name.SELECT_TABLE, ImmutableSet.of("read", "select"))
+ .build();
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ * Reference: https://github.com/apache/gravitino/issues/4509
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject(role.name(), (RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @VisibleForTesting
+ public List<Privilege> getAllPrivileges() {
+ return mapPrivileges.keySet().stream().map(Privileges::allow).collect(Collectors.toList());
+ }
+
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ List<Privilege> allPrivileges = getAllPrivileges();
+
+ SecurableObject securableObjects =
+ SecurableObjects.parse(metadataObject.fullName(), metadataObject.type(), allPrivileges);
+
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentUserName())
+ .withCreateTime(Instant.now())
+ .build();
+
+ RoleEntity role =
+ RoleEntity.builder()
+ .withId(0L)
+ .withName(OWNER_ROLE_NAME)
+ .withAuditInfo(auditInfo)
+ .withSecurableObjects(Lists.newArrayList(securableObjects))
+ .build();
+
+ Boolean execResult = onRoleCreated(role);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(0L)
+ .withName(preOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ execResult = onRevokedRolesFromUser(Lists.newArrayList(role), userEntity);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(0L)
+ .withName(preOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ execResult = onRevokedRolesFromGroup(Lists.newArrayList(role), groupEntity);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(0L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ execResult = onGrantedRolesToUser(Lists.newArrayList(role), userEntity);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(0L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ execResult = onGrantedRolesToGroup(Lists.newArrayList(role), groupEntity);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+ }
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ for (Role role : roles) {
+ role.securableObjects()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn("The policy is not exist for the securable object({})", securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject
+ .privileges()
+ .forEach(
+ privilege -> {
+ // Convert Gravitino privilege to Ranger privilege
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .forEach(
+ // Use the Ranger privilege name to search
+ rangerPrivilegeName -> {
+ policy
+ /**
+ * TODO: Maybe we need to add the user to the
+ * Deny/DataMask/RowFilter policy item in the future.
+ */
+ .getPolicyItems()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilegeName))) {
+ // If the user is not exist in the policy item, then
+ // add it.
+ if (!policyItem.getUsers().contains(user.name())) {
+ policyItem.getUsers().add(user.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ AtomicReference<Boolean> result = new AtomicReference<>(Boolean.TRUE);
+ for (Role role : roles) {
+ role.securableObjects()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn("The policy is not exist for the securable object({})", securableObject);
+ result.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject
+ .privileges()
+ .forEach(
+ privilege -> {
+ // Convert Gravitino privilege to Ranger privilege
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .forEach(
+ // Use the Ranger privilege name to search
+ rangerPrivilegeName -> {
+ policy
+ // TODO: Maybe we need to add the user to the
+ // Deny/DataMask/RowFilter policy item in the future.
+ .getPolicyItems()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilegeName))) {
+ // If the user is exist in the policy item, then
+ // remove it.
+ policyItem.getUsers().removeIf(user.name()::equals);
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ if (!result.get()) {
+ return Boolean.FALSE;
+ }
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ AtomicReference<Boolean> result = new AtomicReference<>(Boolean.TRUE);
+ for (Role role : roles) {
+ role.securableObjects()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn("The policy is not exist for the securable object({})", securableObject);
+ result.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject
+ .privileges()
+ .forEach(
+ privilege -> {
+ // Convert Gravitino privilege to Ranger privilege
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .forEach(
+ // Use the Ranger privilege name to search
+ rangerPrivilegeName -> {
+ policy
+ // TODO: Maybe we need to add the user to the
+ // Deny/DataMask/RowFilter policy item in the future.
+ .getPolicyItems()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilegeName))) {
+ // If the user is not exist in the policy item, then
+ // add it.
+ if (!policyItem
+ .getGroups()
+ .contains(group.name())) {
+ policyItem.getGroups().add(group.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ if (!result.get()) {
+ return Boolean.FALSE;
+ }
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ AtomicReference<Boolean> result = new AtomicReference<>(Boolean.TRUE);
+ for (Role role : roles) {
+ role.securableObjects()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn("The policy is not exist for the securable object({})", securableObject);
+ result.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject
+ .privileges()
+ .forEach(
+ privilege -> {
+ // Convert Gravitino privilege to Ranger privilege
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .forEach(
+ // Use the Ranger privilege name to search
+ rangerPrivilegeName -> {
+ policy
+ // TODO: Maybe we need to add the user to the
+ // Deny/DataMask/RowFilter policy item in the future.
+ .getPolicyItems()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilegeName))) {
+ // If the user is exist in the policy item, then
+ // remove it.
+ policyItem
+ .getGroups()
+ .removeIf(group.name()::equals);
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ if (!result.get()) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the securable object. <br>
+ * 2. If the policy is exist and have same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy is exist but have different privilege, also return true. Because one Ranger
+ * policy maybe contain multiple Gravitino securable object <br>
+ * 4. If the policy is not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(String roleName, RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If exist policy and have same privilege then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(formatPolicyName(roleName, change.getSecurableObject().fullName()));
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> metadataObjectNamespaces =
+ Lists.newArrayList(
+ SecurableObjects.DOT_SPLITTER.splitToList(change.getSecurableObject().fullName()));
+ if (metadataObjectNamespaces.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ metadataObjectNamespaces.remove(0); // remove `catalog`
Review Comment:
Why do we not need to set the catalog in `PolicyResource`, how do we uniquely identify the resource during authorization?
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHiveAuthorizationPlugin.java:
##########
@@ -0,0 +1,840 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Privileges;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * RangerHiveAuthorizationPlugin is a plugin for Apache Ranger to manage the Hive authorization of
+ * the Apache Gravitino.
+ */
+public class RangerHiveAuthorizationPlugin extends RangerAuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerHiveAuthorizationPlugin.class);
+
+ public RangerHiveAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+ }
+
+ /**
+ * Ranger hive's privilege have `select`, `update`, `create`, `drop`, `alter`, `index`, `lock`,
+ * `read`, `write`, `repladmin`, `serviceadmin`, `refresh` and `all`.
+ *
+ * <p>Reference: ranger/agents-common/src/main/resources/service-defs/ranger-servicedef-hive.json
+ */
+ @Override
+ protected void initMapPrivileges() {
+ mapPrivileges =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(Privilege.Name.CREATE_SCHEMA, ImmutableSet.of("create"))
+ .put(Privilege.Name.CREATE_TABLE, ImmutableSet.of("create"))
+ .put(Privilege.Name.MODIFY_TABLE, ImmutableSet.of("update", "drop", "alter", "write"))
+ .put(Privilege.Name.SELECT_TABLE, ImmutableSet.of("read", "select"))
+ .build();
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
Review Comment:
How to understand "Ranger does not have Role concept"?
I understand that Ranger have the roles, and we can use the `rangerClient` to create and delete roles.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1722751373
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHiveAuthorizationPlugin.java:
##########
@@ -0,0 +1,86 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Set;
+import org.apache.gravitino.authorization.Privilege;
+
+/**
+ * RangerHiveAuthorizationPlugin is a plugin for Apache Ranger to manage the Hive authorization of
+ * the Apache Gravitino.
+ */
+public class RangerHiveAuthorizationPlugin extends RangerAuthorizationPlugin {
+ public RangerHiveAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super(catalogProvider, config);
+ }
+
+ /**
+ * Ranger hive's privilege have `select`, `update`, `create`, `drop`, `alter`, `index`, `lock`,
+ * `read`, `write`, `repladmin`, `serviceadmin`, `refresh` and `all`. Reference:
+ * ranger/agents-common/src/main/resources/service-defs/ranger-servicedef-hive.json
+ */
+ @Override
+ protected void initMapPrivileges() {
+ mapPrivileges =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.MODIFY_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_UPDATE,
+ RangerDefines.ACCESS_TYPE_HIVE_ALTER,
+ RangerDefines.ACCESS_TYPE_HIVE_WRITE))
Review Comment:
Does Ranger have the privilege delete table?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1722762287
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
Review Comment:
What's the difference between filter keys and precise filter keys?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1723286789
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ mapAccesses.put(access.getType(), true);
+ });
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy exists but has different privileges, also return true. Because one Ranger
+ * policy maybe contain multiple Gravitino securable object <br>
+ * 4. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravition securable object's privilege
Review Comment:
```suggestion
// Check the policy item's accesses and roles equal the Gravitino securable object's privilege
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1723281358
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
Review Comment:
```suggestion
* 1. Create a group in the Ranger if the group doesn't exist. <br>
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1722592797
##########
core/src/main/java/org/apache/gravitino/connector/authorization/UserGroupAuthorizationPlugin.java:
##########
@@ -98,46 +98,15 @@ interface UserGroupAuthorizationPlugin {
Boolean onGroupAcquired(Group group) throws RuntimeException;
/**
- * After granting roles to a user from Gravitino, this method is called to grant roles to the user
- * in the underlying system. <br>
- *
- * @param user The entity of the User.
- * @param roles The entities of the Roles.
- * @return True if the Grant was successful, false if the Grant was failed.
- * @throws RuntimeException If granting roles to a user encounters storage issues.
- */
- Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException;
-
- /**
- * After revoking roles from a user from Gravitino, this method is called to revoke roles from the
- * user in the underlying system. <br>
- *
- * @param user The entity of the User.
- * @param roles The entities of the Roles.
- * @return True if the revoke was successfully removed, false if the revoke failed.
- * @throws RuntimeException If revoking roles from a user encounters storage issues.
- */
- Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException;
-
- /**
- * After granting roles to a group from Gravitino, this method is called to grant roles to the
- * group in the underlying system. <br>
- *
- * @param group The entity of the Group.
- * @param roles The entities of the Roles.
- * @return True if the revoke was successfully removed, False if the revoke failed.
- * @throws RuntimeException If granting roles to a group encounters storage issues.
- */
- Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException;
-
- /**
- * After revoking roles from a group from Gravitino, this method is called to revoke roles from
- * the group in the underlying system. <br>
+ * After set a Owner to Gravitino, this method is called to set the Owner to the underlying
+ * system. <br>
*
- * @param group The entity of the Group.
- * @param roles The entities of the Roles.
- * @return True if the revoke was successfully removed, False if the revoke failed.
- * @throws RuntimeException If revoking roles from a group encounters storage issues.
+ * @param metadataObject The metadata entity.
+ * @param preOwner The previous owner.
+ * @param newOwner The new owner.
+ * @return True if the set Owner was successfully set, false if the set Owner failed.
+ * @throws RuntimeException If adding the Group encounters storage issues.
*/
- Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException;
+ Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
Review Comment:
Need I raise another pull request?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724520020
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,998 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have a Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contains multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
Review Comment:
Do you need to judge the return value?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724536521
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,998 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have a Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contains multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Grant role: {} to group: {} failed!", role, group, e);
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from group: {} failed!", role, group, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users =
+ StringUtils.isEmpty(userName) ? Sets.newHashSet() : Sets.newHashSet(userName);
+ Set<String> groups =
+ StringUtils.isEmpty(groupName) ? Sets.newHashSet() : Sets.newHashSet(groupName);
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(Sets.newHashSet(roleName));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception, if the role does not exist, we will then create it.
+ LOG.warn("The role({}) is not exist in the Ranger!", roleName);
+ }
+
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manually precisely filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are managed by Gravitino.
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ mapAccesses.put(access.getType(), true);
+ });
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy exists but has different privileges, also return true. Because one Ranger
+ * policy maybe contain multiple Gravitino securable object <br>
+ * 4. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravitino securable object's privilege
+ // and roleName
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If it exists policy with the same privilege, then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(change.getSecurableObject().fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(
+ SecurableObjects.DOT_SPLITTER.splitToList(change.getSecurableObject().fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ List<String> rangerDefinesList =
+ Lists.newArrayList(
+ RangerDefines.RESOURCE_DATABASE,
+ RangerDefines.RESOURCE_TABLE,
+ RangerDefines.RESOURCE_COLUMN);
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy.getResources().put(rangerDefinesList.get(i), policyResource);
+ }
+ }
+
+ addPolicyItem(policy, change.getRoleName(), change.getSecurableObject());
+ try {
Review Comment:
Maybe you can extract a method `CreateOrUpdatePolicy` in `PolicyUtil` or `PolicyHelper` class.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724753819
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,583 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.authorization.ranger.reference.VXGroup;
+import org.apache.gravitino.authorization.ranger.reference.VXGroupList;
+import org.apache.gravitino.authorization.ranger.reference.VXUser;
+import org.apache.gravitino.authorization.ranger.reference.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Ranger authorization operations plugin abstract class. <br>
+ * 1. For Ranger limit, The same metadata object only has a unique Ranger policy, So a Ranger policy
+ * maybe contains multiple Gravitino securable objects. <br>
+ * 2. For easy management, each Ranger privilege will create one RangerPolicyItemAccess in the
+ * policy. <br>
+ * 3. Ranger also have Role concept, and support adds multiple users or groups in the Ranger Role,
+ * So we can use the Ranger Role to implement the Gravitino Role. <br>
+ * 4. The Ranger policy also supports multiple users and groups, But we only use a user or group to
+ * implement Gravitino Owner concept. <br>
+ */
+public class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected String rangerServiceName;
+ protected RangerClientExtend rangerClient;
+ private RangerHelper rangerHelper;
+ @VisibleForTesting public final String rangerAdminName;
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ rangerAdminName = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ RangerHelper.check(rangerUrl != null, "Ranger admin URL is required");
+ RangerHelper.check(authType != null, "Ranger auth type is required");
+ RangerHelper.check(rangerAdminName != null, "Ranger username is required");
+ RangerHelper.check(password != null, "Ranger password is required");
+ RangerHelper.check(rangerServiceName != null, "Ranger service name is required");
+ rangerClient = new RangerClientExtend(rangerUrl, authType, rangerAdminName, password);
+ rangerHelper = new RangerHelper(this, catalogProvider);
+ }
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return rangerHelper.privilegesMapping.get(name);
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(rangerHelper.ownerPrivileges);
+ }
+
+ /**
+ * Create a new role in the Ranger. <br>
+ * 1. Create a policy for metadata object. <br>
+ * 2. Save role name in the Policy items. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ return rangerHelper.checkRangerRole(role.name());
+ }
+
+ /** Remove the role name from the Ranger policy item, and delete this Role in the Ranger. <br> */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, delete the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), rangerAdminName, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult = doRemoveSecurableObject((RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult = doUpdateSecurableObject((RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ * 1. If the metadata object already has an owner, then transfer the ownership from preOwner to
+ * newOwner, The function params preOwner and newOwner don't equal null. <br>
+ * 2. If the metadata object doesn't have an owner, then set the owner to newOwner, The function
+ * params preOwner equal null and newOwner don't equal null. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object.
+ * @param newOwner The new owner of the metadata object.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ RangerHelper.check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = rangerHelper.findManagedPolicy(metadataObject);
+ try {
+ if (policy == null) {
+ policy = rangerHelper.addOwnerToNewPolicy(metadataObject, newOwner);
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerHelper.updatePolicyOwner(policy, preOwner, newOwner);
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this user to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param user The user to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role: {} to user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this user from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param user The user to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this group to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Grant role: {} to group: {} failed!", role, group, e);
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this group from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param group The group to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from group: {} failed!", role, group, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
Review Comment:
```suggestion
LOG.warn("The group({}) doesn't exist in the Ranger!", group);
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724775759
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ mapAccesses.put(access.getType(), true);
+ });
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy exists but has different privileges, also return true. Because one Ranger
+ * policy maybe contain multiple Gravitino securable object <br>
+ * 4. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravition securable object's privilege
+ // and roleName
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If exist policy and have same privilege then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(change.getSecurableObject().fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(
+ SecurableObjects.DOT_SPLITTER.splitToList(change.getSecurableObject().fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+ }
+
+ addPolicyItem(policy, change.getRoleName(), change.getSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return true;
+ }
+
+ /**
+ * Remove the securable object's privilege from the policy. <br>
+ * Because Ranger use unique metadata to location Ranger policy and manage the all privileges, So
+ * one Ranger policy maybe contain multiple Gravitino privilege objects. <br>
+ * Remove Ranger policy item condition is: <br>
+ * 1. This Ranger policy item's accesses equal the Gravition securable object's privilege. <br>
+ * 2. This Ranger policy item's users and groups is empty. <br>
+ * If policy didn't have any policy item, then delete this policy: <br>
+ */
+ private boolean doRemoveSecurableObject(
+ String roleName, RoleChange.RemoveSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ policy
+ .getPolicyItems()
+ .forEach(
+ policyItem -> {
+ boolean match =
+ policyItem.getAccesses().stream()
+ .allMatch(
+ // Find the policy item that match access and role
+ access -> {
+ // Use Gravitino privilege to search the Ranger policy item's access
+ boolean matchPrivilege =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(
+ privilege ->
+ translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .anyMatch(privilege -> privilege.equals(access.getType()));
+ return matchPrivilege;
+ });
+ if (match) {
+ policyItem.getRoles().removeIf(roleName::equals);
+ }
+ });
+
+ // If the policy does have any role and user and group, then remove it.
+ policy
+ .getPolicyItems()
+ .removeIf(
+ policyItem ->
+ policyItem.getRoles().isEmpty()
+ && policyItem.getUsers().isEmpty()
+ && policyItem.getGroups().isEmpty());
+
+ try {
+ if (policy.getPolicyItems().size() == 0) {
+ rangerClient.deletePolicy(policy.getId());
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ LOG.error("Failed to remove the policy item from the Ranger policy {}!", policy);
+ throw new RuntimeException(e);
+ }
+ } else {
+ LOG.warn(
+ "Cannot find the Ranger policy({}) for the Gravitino securable object({})!",
+ roleName,
+ change.getSecurableObject().fullName());
+ // Don't throw exception or return false, because need support immutable operation.
+ }
+ return true;
+ }
+
+ /**
+ * 1. Find the policy base securable object. <br>
+ * 2. If the policy is exist, then user new securable object's privilege to update. <br>
+ * 3. If the policy is not exist return false. <br>
+ */
+ private boolean doUpdateSecurableObject(
+ String roleName, RoleChange.UpdateSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ removePolicyItem(policy, roleName, change.getSecurableObject());
+ addPolicyItem(policy, roleName, change.getNewSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ } else {
+ LOG.warn(
+ "Cannot find the policy({}) for the securable object({})!",
+ roleName,
+ change.getSecurableObject().fullName());
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Add policy item access items base the securable object's privileges. <br>
+ * We didn't clean the policy items, because one Ranger policy maybe contain multiple Gravitino
+ * securable objects. <br>
+ */
+ private void addPolicyItem(
+ RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkSecurableObject(securableObject);
+
+ // Add the policy items by the securable object's privileges
+ securableObject
+ .privileges()
+ .forEach(
+ gravitinoPrivilege -> {
+ // Translate the Gravitino privilege to map Ranger privilege
+ translatePrivilege(gravitinoPrivilege.name())
+ .forEach(
+ mappedPrivilege -> {
+ // Find the policy item that matches Gravitino privilege
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItems =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ access -> access.getType().equals(mappedPrivilege));
+ })
+ .collect(Collectors.toList());
+
+ if (matchPolicyItems.size() == 0) {
+ // If the policy item does not exist, then create a new policy item
+ RangerPolicy.RangerPolicyItem policyItem =
+ new RangerPolicy.RangerPolicyItem();
+ RangerPolicy.RangerPolicyItemAccess access =
+ new RangerPolicy.RangerPolicyItemAccess();
+ access.setType(mappedPrivilege);
+ policyItem.getAccesses().add(access);
+ policyItem.getRoles().add(roleName);
+ if (Privilege.Condition.ALLOW == gravitinoPrivilege.condition()) {
+ policy.getPolicyItems().add(policyItem);
+ } else {
+ policy.getDenyPolicyItems().add(policyItem);
+ }
+ } else {
+ // If the policy item exists, then add the role to the policy item
+ matchPolicyItems.stream()
+ .forEach(
+ policyItem -> {
+ // If the role is not in the policy item, then add it
+ if (!policyItem.getRoles().contains(roleName)) {
+ policyItem.getRoles().add(roleName);
+ }
+ });
+ }
+ });
+ });
+ }
+
+ /**
+ * Remove policy item base the securable object's privileges and role name. <br>
+ * We didn't directly clean the policy items, because one Ranger policy maybe contain multiple
+ * Gravitino privilege objects. <br>
+ */
+ private void removePolicyItem(
+ RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkSecurableObject(securableObject);
+
+ // Delete the policy role base the securable object's privileges
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ boolean matchPrivilege =
+ securableObject.privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .anyMatch(
+ privilege -> {
+ return access.getType().equals(privilege);
+ });
+ if (matchPrivilege
+ && !policyItem.getUsers().isEmpty()
+ && !policyItem.getGroups().isEmpty()) {
+ // Not ownership policy item, then remove the role
+ policyItem.getRoles().removeIf(roleName::equals);
+ }
+ });
+ });
+
+ // Delete the policy items if the roles is empty and not ownership policy item
+ policy
+ .getPolicyItems()
+ .removeIf(
+ policyItem -> {
+ return policyItem.getRoles().isEmpty()
+ && policyItem.getUsers().isEmpty()
+ && policyItem.getGroups().isEmpty();
+ });
+ }
+
+ private boolean checkSecurableObject(SecurableObject securableObject) {
+ securableObject
+ .privileges()
+ .forEach(
+ privilege -> {
+ check(
+ checkPrivilege(privilege.name()),
+ "This privilege %s is not support in the Ranger hive authorization",
Review Comment:
@xunliu Could you reply this?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#issuecomment-2301631113
> > Does it support multiple Hive catalog uses one Ranger?
>
> Yes, we support. Because each Hive catalog have a separate AuthorizationPlugin instance.
All the authorization plugin uses the same label. Won't it influence each other?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724881433
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,583 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.authorization.ranger.reference.VXGroup;
+import org.apache.gravitino.authorization.ranger.reference.VXGroupList;
+import org.apache.gravitino.authorization.ranger.reference.VXUser;
+import org.apache.gravitino.authorization.ranger.reference.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Ranger authorization operations plugin abstract class. <br>
+ * 1. For Ranger limit, The same metadata object only has a unique Ranger policy, So a Ranger policy
+ * maybe contains multiple Gravitino securable objects. <br>
+ * 2. For easy management, each Ranger privilege will create one RangerPolicyItemAccess in the
+ * policy. <br>
+ * 3. Ranger also have Role concept, and support adds multiple users or groups in the Ranger Role,
+ * So we can use the Ranger Role to implement the Gravitino Role. <br>
+ * 4. The Ranger policy also supports multiple users and groups, But we only use a user or group to
+ * implement Gravitino Owner concept. <br>
+ */
+public class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected String rangerServiceName;
+ protected RangerClientExtend rangerClient;
+ private RangerHelper rangerHelper;
+ @VisibleForTesting public final String rangerAdminName;
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ rangerAdminName = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ RangerHelper.check(rangerUrl != null, "Ranger admin URL is required");
+ RangerHelper.check(authType != null, "Ranger auth type is required");
+ RangerHelper.check(rangerAdminName != null, "Ranger username is required");
+ RangerHelper.check(password != null, "Ranger password is required");
+ RangerHelper.check(rangerServiceName != null, "Ranger service name is required");
+ rangerClient = new RangerClientExtend(rangerUrl, authType, rangerAdminName, password);
+ rangerHelper = new RangerHelper(this, catalogProvider);
+ }
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return rangerHelper.privilegesMapping.get(name);
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(rangerHelper.ownerPrivileges);
+ }
+
+ /**
+ * Create a new role in the Ranger. <br>
+ * 1. Create a policy for metadata object. <br>
+ * 2. Save role name in the Policy items. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ return rangerHelper.checkRangerRole(role.name());
+ }
+
+ /** Remove the role name from the Ranger policy item, and delete this Role in the Ranger. <br> */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, delete the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), rangerAdminName, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult = doRemoveSecurableObject((RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult = doUpdateSecurableObject((RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ * 1. If the metadata object already has an owner, then transfer the ownership from preOwner to
+ * newOwner, The function params preOwner and newOwner don't equal null. <br>
+ * 2. If the metadata object doesn't have an owner, then set the owner to newOwner, The function
+ * params preOwner equal null and newOwner don't equal null. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object.
+ * @param newOwner The new owner of the metadata object.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ RangerHelper.check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = rangerHelper.findManagedPolicy(metadataObject);
+ try {
+ if (policy == null) {
+ policy = rangerHelper.addOwnerToNewPolicy(metadataObject, newOwner);
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerHelper.updatePolicyOwner(policy, preOwner, newOwner);
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this user to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param user The user to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role: {} to user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this user from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param user The user to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
Review Comment:
<img width="1064" alt="image" src="https://github.com/user-attachments/assets/c33f1a5f-eac7-4a9c-897c-9e26b91ea5d3">
So, when will the role be null in the method above?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "lw-yang (via GitHub)" <gi...@apache.org>.
lw-yang commented on PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#issuecomment-2288800257
I found that there are differences between the construction the ranger policy and our implementation.
If the policyName is `roleName + securableObjectFullName`, it's possible that there will be many policies for the same resource, which seems unnecessary.
In our system, each policy corresponds to a single resource, and the policy is named based on the resource name. Within Ranger, we create roles in ranger, instead of putting the role in the policyName, we will put the role and role privileges into policyItems.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724800112
##########
authorizations/authorization-ranger/src/main/resources/META-INF/services/org.apache.gravitino.connector.authorization.AuthorizationProvider:
##########
@@ -0,0 +1,19 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+org.apache.gravitino.authorization.ranger.RangerAuthorization
Review Comment:
We could only use RangerAuthorization for all catalogs. This seems not ok if we only support partial catalog authorization.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724863560
##########
authorizations/authorization-ranger/src/main/resources/META-INF/services/org.apache.gravitino.connector.authorization.AuthorizationProvider:
##########
@@ -0,0 +1,19 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+org.apache.gravitino.authorization.ranger.RangerAuthorization
Review Comment:
OK, I got it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724147432
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/defines/RangerCommonEnums.java:
##########
@@ -0,0 +1,29 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger.defines;
+
+// apache/ranger/security-admin/src/main/java/org/apache/ranger/defines/RangerCommonEnums.java
+public class RangerCommonEnums {
+ /** IS_VISIBLE is an element of enum VisibilityStatus. Its value is "IS_VISIBLE". */
+ public static final int IS_VISIBLE = 1;
Review Comment:
This variable reference from Apache Ranger, I think we need to keep original shape.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
Review Comment:
This function `findManagedPolicy()` has 57 lines code and 8 lines of comments. I think it is ok.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
Review Comment:
If you have good idea, please tell me, Thanks.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
Review Comment:
I think it is ok.
If you have a good idea, please give me a sample code.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ mapAccesses.put(access.getType(), true);
+ });
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy exists but has different privileges, also return true. Because one Ranger
+ * policy maybe contain multiple Gravitino securable object <br>
+ * 4. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravition securable object's privilege
+ // and roleName
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If exist policy and have same privilege then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(change.getSecurableObject().fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(
+ SecurableObjects.DOT_SPLITTER.splitToList(change.getSecurableObject().fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
Review Comment:
This is good idea.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ mapAccesses.put(access.getType(), true);
+ });
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy exists but has different privileges, also return true. Because one Ranger
+ * policy maybe contain multiple Gravitino securable object <br>
+ * 4. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravition securable object's privilege
+ // and roleName
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If exist policy and have same privilege then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(change.getSecurableObject().fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(
+ SecurableObjects.DOT_SPLITTER.splitToList(change.getSecurableObject().fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+ }
+
+ addPolicyItem(policy, change.getRoleName(), change.getSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return true;
+ }
+
+ /**
+ * Remove the securable object's privilege from the policy. <br>
+ * Because Ranger use unique metadata to location Ranger policy and manage the all privileges, So
+ * one Ranger policy maybe contain multiple Gravitino privilege objects. <br>
+ * Remove Ranger policy item condition is: <br>
+ * 1. This Ranger policy item's accesses equal the Gravition securable object's privilege. <br>
+ * 2. This Ranger policy item's users and groups is empty. <br>
+ * If policy didn't have any policy item, then delete this policy: <br>
+ */
+ private boolean doRemoveSecurableObject(
+ String roleName, RoleChange.RemoveSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ policy
+ .getPolicyItems()
+ .forEach(
+ policyItem -> {
+ boolean match =
+ policyItem.getAccesses().stream()
+ .allMatch(
+ // Find the policy item that match access and role
+ access -> {
+ // Use Gravitino privilege to search the Ranger policy item's access
+ boolean matchPrivilege =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(
+ privilege ->
+ translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .anyMatch(privilege -> privilege.equals(access.getType()));
+ return matchPrivilege;
+ });
+ if (match) {
+ policyItem.getRoles().removeIf(roleName::equals);
+ }
+ });
+
+ // If the policy does have any role and user and group, then remove it.
+ policy
+ .getPolicyItems()
+ .removeIf(
+ policyItem ->
+ policyItem.getRoles().isEmpty()
+ && policyItem.getUsers().isEmpty()
+ && policyItem.getGroups().isEmpty());
+
+ try {
+ if (policy.getPolicyItems().size() == 0) {
+ rangerClient.deletePolicy(policy.getId());
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ LOG.error("Failed to remove the policy item from the Ranger policy {}!", policy);
+ throw new RuntimeException(e);
+ }
+ } else {
+ LOG.warn(
+ "Cannot find the Ranger policy({}) for the Gravitino securable object({})!",
+ roleName,
+ change.getSecurableObject().fullName());
+ // Don't throw exception or return false, because need support immutable operation.
+ }
+ return true;
+ }
+
+ /**
+ * 1. Find the policy base securable object. <br>
+ * 2. If the policy is exist, then user new securable object's privilege to update. <br>
+ * 3. If the policy is not exist return false. <br>
+ */
+ private boolean doUpdateSecurableObject(
+ String roleName, RoleChange.UpdateSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ removePolicyItem(policy, roleName, change.getSecurableObject());
+ addPolicyItem(policy, roleName, change.getNewSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ } else {
+ LOG.warn(
+ "Cannot find the policy({}) for the securable object({})!",
+ roleName,
+ change.getSecurableObject().fullName());
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Add policy item access items base the securable object's privileges. <br>
+ * We didn't clean the policy items, because one Ranger policy maybe contain multiple Gravitino
+ * securable objects. <br>
+ */
+ private void addPolicyItem(
+ RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkSecurableObject(securableObject);
+
+ // Add the policy items by the securable object's privileges
+ securableObject
+ .privileges()
+ .forEach(
+ gravitinoPrivilege -> {
+ // Translate the Gravitino privilege to map Ranger privilege
+ translatePrivilege(gravitinoPrivilege.name())
+ .forEach(
+ mappedPrivilege -> {
+ // Find the policy item that matches Gravitino privilege
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItems =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ access -> access.getType().equals(mappedPrivilege));
+ })
+ .collect(Collectors.toList());
+
Review Comment:
Yes, We need to process Deny and Allow privilege.
But this PR is very big, I think I can finish this issue in the next E2E integration test PR.
I already finish E2E IT https://github.com/xunliu/gravitino/blob/issue-3963-4460/integration-test/src/test/java/org/apache/gravitino/integration/test/authorization/ranger/RangerHiveAuthorizationIT.java
waiting pull request.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ mapAccesses.put(access.getType(), true);
+ });
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy exists but has different privileges, also return true. Because one Ranger
+ * policy maybe contain multiple Gravitino securable object <br>
+ * 4. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravition securable object's privilege
+ // and roleName
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If exist policy and have same privilege then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(change.getSecurableObject().fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(
+ SecurableObjects.DOT_SPLITTER.splitToList(change.getSecurableObject().fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+ }
+
+ addPolicyItem(policy, change.getRoleName(), change.getSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return true;
+ }
+
+ /**
+ * Remove the securable object's privilege from the policy. <br>
+ * Because Ranger use unique metadata to location Ranger policy and manage the all privileges, So
+ * one Ranger policy maybe contain multiple Gravitino privilege objects. <br>
+ * Remove Ranger policy item condition is: <br>
+ * 1. This Ranger policy item's accesses equal the Gravition securable object's privilege. <br>
+ * 2. This Ranger policy item's users and groups is empty. <br>
+ * If policy didn't have any policy item, then delete this policy: <br>
+ */
+ private boolean doRemoveSecurableObject(
+ String roleName, RoleChange.RemoveSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ policy
+ .getPolicyItems()
+ .forEach(
+ policyItem -> {
+ boolean match =
+ policyItem.getAccesses().stream()
+ .allMatch(
+ // Find the policy item that match access and role
+ access -> {
+ // Use Gravitino privilege to search the Ranger policy item's access
+ boolean matchPrivilege =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(
+ privilege ->
+ translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .anyMatch(privilege -> privilege.equals(access.getType()));
+ return matchPrivilege;
+ });
+ if (match) {
+ policyItem.getRoles().removeIf(roleName::equals);
+ }
+ });
+
+ // If the policy does have any role and user and group, then remove it.
+ policy
+ .getPolicyItems()
+ .removeIf(
+ policyItem ->
+ policyItem.getRoles().isEmpty()
+ && policyItem.getUsers().isEmpty()
+ && policyItem.getGroups().isEmpty());
+
+ try {
+ if (policy.getPolicyItems().size() == 0) {
+ rangerClient.deletePolicy(policy.getId());
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ LOG.error("Failed to remove the policy item from the Ranger policy {}!", policy);
+ throw new RuntimeException(e);
+ }
+ } else {
+ LOG.warn(
+ "Cannot find the Ranger policy({}) for the Gravitino securable object({})!",
+ roleName,
+ change.getSecurableObject().fullName());
+ // Don't throw exception or return false, because need support immutable operation.
+ }
+ return true;
+ }
+
+ /**
+ * 1. Find the policy base securable object. <br>
+ * 2. If the policy is exist, then user new securable object's privilege to update. <br>
+ * 3. If the policy is not exist return false. <br>
+ */
+ private boolean doUpdateSecurableObject(
+ String roleName, RoleChange.UpdateSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ removePolicyItem(policy, roleName, change.getSecurableObject());
+ addPolicyItem(policy, roleName, change.getNewSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ } else {
+ LOG.warn(
+ "Cannot find the policy({}) for the securable object({})!",
+ roleName,
+ change.getSecurableObject().fullName());
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Add policy item access items base the securable object's privileges. <br>
+ * We didn't clean the policy items, because one Ranger policy maybe contain multiple Gravitino
+ * securable objects. <br>
+ */
+ private void addPolicyItem(
+ RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkSecurableObject(securableObject);
+
+ // Add the policy items by the securable object's privileges
+ securableObject
+ .privileges()
+ .forEach(
+ gravitinoPrivilege -> {
+ // Translate the Gravitino privilege to map Ranger privilege
+ translatePrivilege(gravitinoPrivilege.name())
+ .forEach(
+ mappedPrivilege -> {
+ // Find the policy item that matches Gravitino privilege
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItems =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ access -> access.getType().equals(mappedPrivilege));
+ })
+ .collect(Collectors.toList());
+
+ if (matchPolicyItems.size() == 0) {
+ // If the policy item does not exist, then create a new policy item
+ RangerPolicy.RangerPolicyItem policyItem =
+ new RangerPolicy.RangerPolicyItem();
+ RangerPolicy.RangerPolicyItemAccess access =
+ new RangerPolicy.RangerPolicyItemAccess();
+ access.setType(mappedPrivilege);
+ policyItem.getAccesses().add(access);
+ policyItem.getRoles().add(roleName);
+ if (Privilege.Condition.ALLOW == gravitinoPrivilege.condition()) {
+ policy.getPolicyItems().add(policyItem);
+ } else {
+ policy.getDenyPolicyItems().add(policyItem);
+ }
+ } else {
+ // If the policy item exists, then add the role to the policy item
+ matchPolicyItems.stream()
+ .forEach(
+ policyItem -> {
+ // If the role is not in the policy item, then add it
+ if (!policyItem.getRoles().contains(roleName)) {
+ policyItem.getRoles().add(roleName);
+ }
+ });
+ }
+ });
+ });
+ }
+
+ /**
+ * Remove policy item base the securable object's privileges and role name. <br>
+ * We didn't directly clean the policy items, because one Ranger policy maybe contain multiple
+ * Gravitino privilege objects. <br>
+ */
+ private void removePolicyItem(
+ RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkSecurableObject(securableObject);
+
+ // Delete the policy role base the securable object's privileges
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ boolean matchPrivilege =
+ securableObject.privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .anyMatch(
+ privilege -> {
+ return access.getType().equals(privilege);
+ });
+ if (matchPrivilege
+ && !policyItem.getUsers().isEmpty()
+ && !policyItem.getGroups().isEmpty()) {
+ // Not ownership policy item, then remove the role
+ policyItem.getRoles().removeIf(roleName::equals);
+ }
+ });
+ });
+
+ // Delete the policy items if the roles is empty and not ownership policy item
+ policy
+ .getPolicyItems()
+ .removeIf(
+ policyItem -> {
+ return policyItem.getRoles().isEmpty()
+ && policyItem.getUsers().isEmpty()
+ && policyItem.getGroups().isEmpty();
+ });
+ }
+
+ private boolean checkSecurableObject(SecurableObject securableObject) {
+ securableObject
+ .privileges()
+ .forEach(
+ privilege -> {
+ check(
+ checkPrivilege(privilege.name()),
+ "This privilege %s is not support in the Ranger hive authorization",
Review Comment:
What unnecessary privileges? please specify
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1722596783
##########
authorizations/authorization-ranger/src/main/resources/META-INF/services/org.apache.gravitino.authorization.ranger.RangerAuthorization:
##########
@@ -0,0 +1,19 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+org.apache.gravitino.authorization.ranger.RangerAuthorization
Review Comment:
User can't use other authorization plugin implement.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1723033479
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
Review Comment:
If you use database=`db` to search policy in the Ranger, Ranger will return All fuzzy match results. just like `db1`, `db2` ...
So we need precise filter.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1723216181
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/defines/RangerCommonEnums.java:
##########
@@ -0,0 +1,29 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger.defines;
+
+// apache/ranger/security-admin/src/main/java/org/apache/ranger/defines/RangerCommonEnums.java
+public class RangerCommonEnums {
+ /** IS_VISIBLE is an element of enum VisibilityStatus. Its value is "IS_VISIBLE". */
+ public static final int IS_VISIBLE = 1;
Review Comment:
The value of `IS_VISBILE` is the same as the `STATUS_ENABLED`, isn't it ok?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1723227774
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ mapAccesses.put(access.getType(), true);
+ });
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy exists but has different privileges, also return true. Because one Ranger
+ * policy maybe contain multiple Gravitino securable object <br>
+ * 4. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravition securable object's privilege
+ // and roleName
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If exist policy and have same privilege then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(change.getSecurableObject().fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(
+ SecurableObjects.DOT_SPLITTER.splitToList(change.getSecurableObject().fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+ }
+
+ addPolicyItem(policy, change.getRoleName(), change.getSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return true;
+ }
+
+ /**
+ * Remove the securable object's privilege from the policy. <br>
+ * Because Ranger use unique metadata to location Ranger policy and manage the all privileges, So
+ * one Ranger policy maybe contain multiple Gravitino privilege objects. <br>
+ * Remove Ranger policy item condition is: <br>
+ * 1. This Ranger policy item's accesses equal the Gravition securable object's privilege. <br>
+ * 2. This Ranger policy item's users and groups is empty. <br>
+ * If policy didn't have any policy item, then delete this policy: <br>
+ */
+ private boolean doRemoveSecurableObject(
+ String roleName, RoleChange.RemoveSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ policy
+ .getPolicyItems()
+ .forEach(
+ policyItem -> {
+ boolean match =
+ policyItem.getAccesses().stream()
+ .allMatch(
+ // Find the policy item that match access and role
+ access -> {
+ // Use Gravitino privilege to search the Ranger policy item's access
+ boolean matchPrivilege =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(
+ privilege ->
+ translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .anyMatch(privilege -> privilege.equals(access.getType()));
+ return matchPrivilege;
+ });
+ if (match) {
+ policyItem.getRoles().removeIf(roleName::equals);
+ }
+ });
+
+ // If the policy does have any role and user and group, then remove it.
+ policy
+ .getPolicyItems()
+ .removeIf(
+ policyItem ->
+ policyItem.getRoles().isEmpty()
+ && policyItem.getUsers().isEmpty()
+ && policyItem.getGroups().isEmpty());
+
+ try {
+ if (policy.getPolicyItems().size() == 0) {
+ rangerClient.deletePolicy(policy.getId());
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ LOG.error("Failed to remove the policy item from the Ranger policy {}!", policy);
+ throw new RuntimeException(e);
+ }
+ } else {
+ LOG.warn(
+ "Cannot find the Ranger policy({}) for the Gravitino securable object({})!",
+ roleName,
+ change.getSecurableObject().fullName());
+ // Don't throw exception or return false, because need support immutable operation.
+ }
+ return true;
+ }
+
+ /**
+ * 1. Find the policy base securable object. <br>
+ * 2. If the policy is exist, then user new securable object's privilege to update. <br>
+ * 3. If the policy is not exist return false. <br>
+ */
+ private boolean doUpdateSecurableObject(
+ String roleName, RoleChange.UpdateSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ removePolicyItem(policy, roleName, change.getSecurableObject());
+ addPolicyItem(policy, roleName, change.getNewSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ } else {
+ LOG.warn(
+ "Cannot find the policy({}) for the securable object({})!",
+ roleName,
+ change.getSecurableObject().fullName());
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Add policy item access items base the securable object's privileges. <br>
+ * We didn't clean the policy items, because one Ranger policy maybe contain multiple Gravitino
+ * securable objects. <br>
+ */
+ private void addPolicyItem(
+ RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkSecurableObject(securableObject);
+
+ // Add the policy items by the securable object's privileges
+ securableObject
+ .privileges()
+ .forEach(
+ gravitinoPrivilege -> {
+ // Translate the Gravitino privilege to map Ranger privilege
+ translatePrivilege(gravitinoPrivilege.name())
+ .forEach(
+ mappedPrivilege -> {
+ // Find the policy item that matches Gravitino privilege
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItems =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ access -> access.getType().equals(mappedPrivilege));
+ })
+ .collect(Collectors.toList());
+
+ if (matchPolicyItems.size() == 0) {
+ // If the policy item does not exist, then create a new policy item
+ RangerPolicy.RangerPolicyItem policyItem =
+ new RangerPolicy.RangerPolicyItem();
+ RangerPolicy.RangerPolicyItemAccess access =
+ new RangerPolicy.RangerPolicyItemAccess();
+ access.setType(mappedPrivilege);
+ policyItem.getAccesses().add(access);
+ policyItem.getRoles().add(roleName);
+ if (Privilege.Condition.ALLOW == gravitinoPrivilege.condition()) {
+ policy.getPolicyItems().add(policyItem);
+ } else {
+ policy.getDenyPolicyItems().add(policyItem);
+ }
+ } else {
+ // If the policy item exists, then add the role to the policy item
+ matchPolicyItems.stream()
+ .forEach(
+ policyItem -> {
+ // If the role is not in the policy item, then add it
+ if (!policyItem.getRoles().contains(roleName)) {
+ policyItem.getRoles().add(roleName);
+ }
+ });
+ }
+ });
+ });
+ }
+
+ /**
+ * Remove policy item base the securable object's privileges and role name. <br>
+ * We didn't directly clean the policy items, because one Ranger policy maybe contain multiple
+ * Gravitino privilege objects. <br>
+ */
+ private void removePolicyItem(
+ RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkSecurableObject(securableObject);
+
+ // Delete the policy role base the securable object's privileges
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ boolean matchPrivilege =
+ securableObject.privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .anyMatch(
+ privilege -> {
+ return access.getType().equals(privilege);
+ });
+ if (matchPrivilege
+ && !policyItem.getUsers().isEmpty()
+ && !policyItem.getGroups().isEmpty()) {
+ // Not ownership policy item, then remove the role
+ policyItem.getRoles().removeIf(roleName::equals);
+ }
+ });
+ });
+
+ // Delete the policy items if the roles is empty and not ownership policy item
+ policy
+ .getPolicyItems()
+ .removeIf(
+ policyItem -> {
+ return policyItem.getRoles().isEmpty()
+ && policyItem.getUsers().isEmpty()
+ && policyItem.getGroups().isEmpty();
+ });
+ }
+
+ private boolean checkSecurableObject(SecurableObject securableObject) {
+ securableObject
+ .privileges()
+ .forEach(
+ privilege -> {
+ check(
+ checkPrivilege(privilege.name()),
+ "This privilege %s is not support in the Ranger hive authorization",
Review Comment:
Some unnecessary privileges will be pushed down underlying systems.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#issuecomment-2298058345
> hi @jerqi
>
> > Do you have e2e tests for this pull request?
>
> Sure, IT in the `RangerHiveIT.java`
Do you start a Gravitino Server in the test?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1722761615
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
Review Comment:
What's the meaning of `manual precise`?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1723289010
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ mapAccesses.put(access.getType(), true);
+ });
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy exists but has different privileges, also return true. Because one Ranger
+ * policy maybe contain multiple Gravitino securable object <br>
+ * 4. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravition securable object's privilege
+ // and roleName
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If exist policy and have same privilege then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(change.getSecurableObject().fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(
+ SecurableObjects.DOT_SPLITTER.splitToList(change.getSecurableObject().fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+ }
+
+ addPolicyItem(policy, change.getRoleName(), change.getSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return true;
+ }
+
+ /**
+ * Remove the securable object's privilege from the policy. <br>
+ * Because Ranger use unique metadata to location Ranger policy and manage the all privileges, So
Review Comment:
```suggestion
* Because Ranger uses unique metadata to location Ranger policy and manage all the privileges, So
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1726200490
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHelper.java:
##########
@@ -0,0 +1,533 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This class is a helper class for the Ranger authorization plugin. It provides the ability to
+ * manage the Ranger policies and roles.
+ */
+public class RangerHelper {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerHelper.class);
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ RangerAuthorizationPlugin rangerAuthorizationPlugin;
+
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ /** The owner privileges, the owner can do anything on the metadata object */
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise search, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, If you use `db.table` condition to search policy, the Ranger will
+ * match `db1.table1`, `db1.table2`, `db*.table*`, So we need to manually precisely filter this
+ * research results. <br>
+ * policySearchKeys: The search Ranger policy condition key defines. <br>
+ * policyPreciseFilterKeys: The precise filter Ranger search results key defines <br>
+ */
+ protected List<String> policySearchKeys = null;
+
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public RangerHelper(RangerAuthorizationPlugin rangerAuthorizationPlugin, String catalogProvider) {
+ this.rangerAuthorizationPlugin = rangerAuthorizationPlugin;
+ switch (catalogProvider) {
+ case "hive":
+ initPrivilegesMapping();
+ initOwnerPrivileges();
+ initPolicySearchKeys();
+ initPreciseFilterKeys();
+ break;
+ default:
+ throw new IllegalArgumentException(
+ "Authorization plugin unsupported catalog provider: " + catalogProvider);
+ }
+ }
+
+ /** Initial mapping Gravitino privilege name to the underlying authorization system privileges. */
+ private void initPrivilegesMapping() {
+ privilegesMapping =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.MODIFY_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_UPDATE,
+ RangerDefines.ACCESS_TYPE_HIVE_ALTER,
+ RangerDefines.ACCESS_TYPE_HIVE_WRITE))
+ .put(
+ Privilege.Name.SELECT_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_READ, RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .build();
+ }
+
+ /** Initial Owner privileges */
+ private void initOwnerPrivileges() {
+ ownerPrivileges = ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_ALL);
+ }
+
+ /** Initial Ranger policy search key defines */
+ private void initPolicySearchKeys() {
+ policySearchKeys =
+ Arrays.asList(
+ RangerDefines.SEARCH_FILTER_DATABASE,
+ RangerDefines.SEARCH_FILTER_TABLE,
+ RangerDefines.SEARCH_FILTER_COLUMN);
+ }
+
+ /** Initial precise filter key defines */
+ private void initPreciseFilterKeys() {
+ policyPreciseFilterKeys =
+ Arrays.asList(
+ RangerDefines.RESOURCE_DATABASE,
+ RangerDefines.RESOURCE_TABLE,
+ RangerDefines.RESOURCE_COLUMN);
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Set<String> setAccesses = new HashSet<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (setAccesses.contains(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ setAccesses.add(access.getType());
+ });
+ }
+
+ /**
+ * Add policy item access items base the securable object's privileges. <br>
+ * We cannot clean the policy items because one Ranger policy maybe contains multiple Gravitino
+ * securable objects. <br>
+ */
+ void addPolicyItem(RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkPrivileges(securableObject);
+
+ // Add the policy items by the securable object's privileges
+ securableObject
+ .privileges()
+ .forEach(
+ gravitinoPrivilege -> {
+ // Translate the Gravitino privilege to map Ranger privilege
+ rangerAuthorizationPlugin
+ .translatePrivilege(gravitinoPrivilege.name())
+ .forEach(
+ mappedPrivilege -> {
+ // Find the policy item that matches Gravitino privilege
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItems =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ access -> access.getType().equals(mappedPrivilege));
+ })
+ .collect(Collectors.toList());
+
+ if (matchPolicyItems.size() == 0) {
+ // If the policy item does not exist, then create a new policy item
+ RangerPolicy.RangerPolicyItem policyItem =
+ new RangerPolicy.RangerPolicyItem();
+ RangerPolicy.RangerPolicyItemAccess access =
+ new RangerPolicy.RangerPolicyItemAccess();
+ access.setType(mappedPrivilege);
+ policyItem.getAccesses().add(access);
+ policyItem.getRoles().add(roleName);
+ if (Privilege.Condition.ALLOW == gravitinoPrivilege.condition()) {
+ policy.getPolicyItems().add(policyItem);
+ } else {
+ policy.getDenyPolicyItems().add(policyItem);
+ }
+ } else {
+ // If the policy item exists, then add the role to the policy item
+ matchPolicyItems.stream()
+ .forEach(
+ policyItem -> {
+ // If the role is not in the policy item, then add it
+ if (!policyItem.getRoles().contains(roleName)) {
+ policyItem.getRoles().add(roleName);
+ }
+ });
+ }
+ });
+ });
+ }
+
+ /**
+ * Remove policy item base the securable object's privileges and role name. <br>
+ * We cannot directly clean the policy items because one Ranger policy maybe contains multiple
+ * Gravitino privilege objects. <br>
+ */
+ void removePolicyItem(RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkPrivileges(securableObject);
+
+ // Delete the policy role base the securable object's privileges
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ boolean matchPrivilege =
+ securableObject.privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(
+ privilege ->
+ rangerAuthorizationPlugin
+ .translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .anyMatch(
+ privilege -> {
+ return access.getType().equals(privilege);
+ });
+ if (matchPrivilege
+ && !policyItem.getUsers().isEmpty()
Review Comment:
Yes, you are right.
I fix this problem and add a test case.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1721662285
##########
core/src/main/java/org/apache/gravitino/connector/authorization/UserGroupAuthorizationPlugin.java:
##########
@@ -98,46 +98,15 @@ interface UserGroupAuthorizationPlugin {
Boolean onGroupAcquired(Group group) throws RuntimeException;
/**
- * After granting roles to a user from Gravitino, this method is called to grant roles to the user
- * in the underlying system. <br>
- *
- * @param user The entity of the User.
- * @param roles The entities of the Roles.
- * @return True if the Grant was successful, false if the Grant was failed.
- * @throws RuntimeException If granting roles to a user encounters storage issues.
- */
- Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException;
-
- /**
- * After revoking roles from a user from Gravitino, this method is called to revoke roles from the
- * user in the underlying system. <br>
- *
- * @param user The entity of the User.
- * @param roles The entities of the Roles.
- * @return True if the revoke was successfully removed, false if the revoke failed.
- * @throws RuntimeException If revoking roles from a user encounters storage issues.
- */
- Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException;
-
- /**
- * After granting roles to a group from Gravitino, this method is called to grant roles to the
- * group in the underlying system. <br>
- *
- * @param group The entity of the Group.
- * @param roles The entities of the Roles.
- * @return True if the revoke was successfully removed, False if the revoke failed.
- * @throws RuntimeException If granting roles to a group encounters storage issues.
- */
- Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException;
-
- /**
- * After revoking roles from a group from Gravitino, this method is called to revoke roles from
- * the group in the underlying system. <br>
+ * After set a Owner to Gravitino, this method is called to set the Owner to the underlying
+ * system. <br>
*
- * @param group The entity of the Group.
- * @param roles The entities of the Roles.
- * @return True if the revoke was successfully removed, False if the revoke failed.
- * @throws RuntimeException If revoking roles from a group encounters storage issues.
+ * @param metadataObject The metadata entity.
+ * @param preOwner The previous owner.
+ * @param newOwner The new owner.
+ * @return True if the set Owner was successfully set, false if the set Owner failed.
+ * @throws RuntimeException If adding the Group encounters storage issues.
*/
- Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException;
+ Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
Review Comment:
We don't call this method yet.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#issuecomment-2296473673
> If we set a schema the privilege read table, will it present schema.* in the Ranger?
Yes
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1723222084
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
Review Comment:
We would better extract a method `applyPreciseFilters` to make code readable.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724783782
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHelper.java:
##########
@@ -0,0 +1,533 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This class is a helper class for the Ranger authorization plugin. It provides the ability to
+ * manage the Ranger policies and roles.
+ */
+public class RangerHelper {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerHelper.class);
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ RangerAuthorizationPlugin rangerAuthorizationPlugin;
+
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ /** The owner privileges, the owner can do anything on the metadata object */
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise search, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, If you use `db.table` condition to search policy, the Ranger will
+ * match `db1.table1`, `db1.table2`, `db*.table*`, So we need to manually precisely filter this
+ * research results. <br>
+ * policySearchKeys: The search Ranger policy condition key defines. <br>
+ * policyPreciseFilterKeys: The precise filter Ranger search results key defines <br>
+ */
+ protected List<String> policySearchKeys = null;
+
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public RangerHelper(RangerAuthorizationPlugin rangerAuthorizationPlugin, String catalogProvider) {
+ this.rangerAuthorizationPlugin = rangerAuthorizationPlugin;
+ switch (catalogProvider) {
+ case "hive":
+ initPrivilegesMapping();
+ initOwnerPrivileges();
+ initPolicySearchKeys();
+ initPreciseFilterKeys();
+ break;
+ default:
+ throw new IllegalArgumentException(
+ "Authorization plugin unsupported catalog provider: " + catalogProvider);
+ }
+ }
+
+ /** Initial mapping Gravitino privilege name to the underlying authorization system privileges. */
+ private void initPrivilegesMapping() {
+ privilegesMapping =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.MODIFY_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_UPDATE,
+ RangerDefines.ACCESS_TYPE_HIVE_ALTER,
+ RangerDefines.ACCESS_TYPE_HIVE_WRITE))
+ .put(
+ Privilege.Name.SELECT_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_READ, RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .build();
+ }
+
+ /** Initial Owner privileges */
+ private void initOwnerPrivileges() {
+ ownerPrivileges = ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_ALL);
+ }
+
+ /** Initial Ranger policy search key defines */
+ private void initPolicySearchKeys() {
+ policySearchKeys =
+ Arrays.asList(
+ RangerDefines.SEARCH_FILTER_DATABASE,
+ RangerDefines.SEARCH_FILTER_TABLE,
+ RangerDefines.SEARCH_FILTER_COLUMN);
+ }
+
+ /** Initial precise filter key defines */
+ private void initPreciseFilterKeys() {
+ policyPreciseFilterKeys =
+ Arrays.asList(
+ RangerDefines.RESOURCE_DATABASE,
+ RangerDefines.RESOURCE_TABLE,
+ RangerDefines.RESOURCE_COLUMN);
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Set<String> setAccesses = new HashSet<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (setAccesses.contains(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ setAccesses.add(access.getType());
+ });
+ }
+
+ /**
+ * Add policy item access items base the securable object's privileges. <br>
+ * We didn't clean the policy items because one Ranger policy maybe contains multiple Gravitino
+ * securable objects. <br>
+ */
+ void addPolicyItem(RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkPrivileges(securableObject);
+
+ // Add the policy items by the securable object's privileges
+ securableObject
+ .privileges()
+ .forEach(
+ gravitinoPrivilege -> {
+ // Translate the Gravitino privilege to map Ranger privilege
+ rangerAuthorizationPlugin
+ .translatePrivilege(gravitinoPrivilege.name())
+ .forEach(
+ mappedPrivilege -> {
Review Comment:
Only two places use this.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724898605
##########
authorizations/authorization-ranger/src/test/java/org/apache/gravitino/authorization/ranger/integration/test/RangerITEnv.java:
##########
@@ -252,7 +257,7 @@ protected static String updateOrCreateRangerPolicy(
if (!policies.isEmpty()) {
// Because Ranger user the wildcard filter, Ranger will return the policy meets
// the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
Review Comment:
Could you modify the comment to align to other places?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1725098417
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHelper.java:
##########
@@ -0,0 +1,533 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This class is a helper class for the Ranger authorization plugin. It provides the ability to
+ * manage the Ranger policies and roles.
+ */
+public class RangerHelper {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerHelper.class);
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ RangerAuthorizationPlugin rangerAuthorizationPlugin;
+
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ /** The owner privileges, the owner can do anything on the metadata object */
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise search, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, If you use `db.table` condition to search policy, the Ranger will
+ * match `db1.table1`, `db1.table2`, `db*.table*`, So we need to manually precisely filter this
+ * research results. <br>
+ * policySearchKeys: The search Ranger policy condition key defines. <br>
+ * policyPreciseFilterKeys: The precise filter Ranger search results key defines <br>
+ */
+ protected List<String> policySearchKeys = null;
+
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public RangerHelper(RangerAuthorizationPlugin rangerAuthorizationPlugin, String catalogProvider) {
+ this.rangerAuthorizationPlugin = rangerAuthorizationPlugin;
+ switch (catalogProvider) {
+ case "hive":
+ initPrivilegesMapping();
+ initOwnerPrivileges();
+ initPolicySearchKeys();
+ initPreciseFilterKeys();
+ break;
+ default:
+ throw new IllegalArgumentException(
+ "Authorization plugin unsupported catalog provider: " + catalogProvider);
+ }
+ }
+
+ /** Initial mapping Gravitino privilege name to the underlying authorization system privileges. */
+ private void initPrivilegesMapping() {
+ privilegesMapping =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.MODIFY_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_UPDATE,
+ RangerDefines.ACCESS_TYPE_HIVE_ALTER,
+ RangerDefines.ACCESS_TYPE_HIVE_WRITE))
+ .put(
+ Privilege.Name.SELECT_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_READ, RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .build();
+ }
+
+ /** Initial Owner privileges */
+ private void initOwnerPrivileges() {
+ ownerPrivileges = ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_ALL);
+ }
+
+ /** Initial Ranger policy search key defines */
+ private void initPolicySearchKeys() {
+ policySearchKeys =
+ Arrays.asList(
+ RangerDefines.SEARCH_FILTER_DATABASE,
+ RangerDefines.SEARCH_FILTER_TABLE,
+ RangerDefines.SEARCH_FILTER_COLUMN);
+ }
+
+ /** Initial precise filter key defines */
+ private void initPreciseFilterKeys() {
+ policyPreciseFilterKeys =
+ Arrays.asList(
+ RangerDefines.RESOURCE_DATABASE,
+ RangerDefines.RESOURCE_TABLE,
+ RangerDefines.RESOURCE_COLUMN);
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Set<String> setAccesses = new HashSet<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (setAccesses.contains(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ setAccesses.add(access.getType());
+ });
+ }
+
+ /**
+ * Add policy item access items base the securable object's privileges. <br>
+ * We cannot clean the policy items because one Ranger policy maybe contains multiple Gravitino
+ * securable objects. <br>
+ */
+ void addPolicyItem(RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkPrivileges(securableObject);
+
+ // Add the policy items by the securable object's privileges
+ securableObject
+ .privileges()
+ .forEach(
+ gravitinoPrivilege -> {
+ // Translate the Gravitino privilege to map Ranger privilege
+ rangerAuthorizationPlugin
+ .translatePrivilege(gravitinoPrivilege.name())
+ .forEach(
+ mappedPrivilege -> {
+ // Find the policy item that matches Gravitino privilege
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItems =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ access -> access.getType().equals(mappedPrivilege));
+ })
+ .collect(Collectors.toList());
+
+ if (matchPolicyItems.size() == 0) {
+ // If the policy item does not exist, then create a new policy item
+ RangerPolicy.RangerPolicyItem policyItem =
+ new RangerPolicy.RangerPolicyItem();
+ RangerPolicy.RangerPolicyItemAccess access =
+ new RangerPolicy.RangerPolicyItemAccess();
+ access.setType(mappedPrivilege);
+ policyItem.getAccesses().add(access);
+ policyItem.getRoles().add(roleName);
+ if (Privilege.Condition.ALLOW == gravitinoPrivilege.condition()) {
+ policy.getPolicyItems().add(policyItem);
+ } else {
+ policy.getDenyPolicyItems().add(policyItem);
+ }
+ } else {
+ // If the policy item exists, then add the role to the policy item
+ matchPolicyItems.stream()
+ .forEach(
+ policyItem -> {
+ // If the role is not in the policy item, then add it
+ if (!policyItem.getRoles().contains(roleName)) {
+ policyItem.getRoles().add(roleName);
+ }
+ });
+ }
+ });
+ });
+ }
+
+ /**
+ * Remove policy item base the securable object's privileges and role name. <br>
+ * We cannot directly clean the policy items because one Ranger policy maybe contains multiple
+ * Gravitino privilege objects. <br>
+ */
+ void removePolicyItem(RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkPrivileges(securableObject);
+
+ // Delete the policy role base the securable object's privileges
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ boolean matchPrivilege =
+ securableObject.privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(
+ privilege ->
+ rangerAuthorizationPlugin
+ .translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .anyMatch(
+ privilege -> {
+ return access.getType().equals(privilege);
+ });
+ if (matchPrivilege
+ && !policyItem.getUsers().isEmpty()
Review Comment:
We just remove roles here, not remove policyItem.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1723046642
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
Review Comment:
Currently, we use admin to execute grant to role.
Just like E2E IT test case.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724462431
##########
integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/RangerContainer.java:
##########
@@ -40,15 +40,18 @@ public class RangerContainer extends BaseContainer {
public static final int RANGER_SERVER_PORT = 6080;
public RangerClient rangerClient;
private String rangerUrl;
- private static final String username = "admin";
- // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
- private static final String password = "rangerR0cks!";
/**
- * for kerberos authentication: authType = "kerberos" username = principal password = path of the
- * keytab file
+ * for kerberos authentication: <br>
+ * authType = "kerberos" <br>
+ * username = principal <br>
+ * password = path of the keytab file <br>
*/
- private static final String authType = "simple";
+ public static final String authType = "simple";
+
+ public static final String rangerUserName = "admin";
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
Review Comment:
OK.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1722755278
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHiveAuthorizationPlugin.java:
##########
@@ -0,0 +1,86 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Set;
+import org.apache.gravitino.authorization.Privilege;
+
+/**
+ * RangerHiveAuthorizationPlugin is a plugin for Apache Ranger to manage the Hive authorization of
+ * the Apache Gravitino.
+ */
+public class RangerHiveAuthorizationPlugin extends RangerAuthorizationPlugin {
+ public RangerHiveAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super(catalogProvider, config);
+ }
+
+ /**
+ * Ranger hive's privilege have `select`, `update`, `create`, `drop`, `alter`, `index`, `lock`,
+ * `read`, `write`, `repladmin`, `serviceadmin`, `refresh` and `all`. Reference:
+ * ranger/agents-common/src/main/resources/service-defs/ranger-servicedef-hive.json
+ */
+ @Override
+ protected void initMapPrivileges() {
+ mapPrivileges =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.MODIFY_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_UPDATE,
+ RangerDefines.ACCESS_TYPE_HIVE_ALTER,
+ RangerDefines.ACCESS_TYPE_HIVE_WRITE))
Review Comment:
Already deleted this privilege in the latest commit.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1723047688
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
Review Comment:
We can consider this case in the `0.6.1`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724518162
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,998 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have a Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
Review Comment:
```suggestion
* Because a Ranger policy maybe contains multiple Gravitino securable objects, <br>
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724512320
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,998 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have a Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
Review Comment:
role may contains `METALAKE` `CREATE_ROLE`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1723038641
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
Review Comment:
Typo `manually precisely filter the policies`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1723288336
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ mapAccesses.put(access.getType(), true);
+ });
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy exists but has different privileges, also return true. Because one Ranger
+ * policy maybe contain multiple Gravitino securable object <br>
+ * 4. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravition securable object's privilege
+ // and roleName
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If exist policy and have same privilege then directly return true, because support
Review Comment:
```suggestion
// If it exists a policy with the same privilege then directly return true, because support
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724333323
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy is not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilege -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilege))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role is not exist. */
+ private RangerRole createRangerRole(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role is not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
Review Comment:
@xunliu This seems more readable.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724485802
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -992,12 +985,11 @@ private boolean checkSecurableObject(SecurableObject securableObject) {
securableObject
.privileges()
.forEach(
- privilege -> {
- check(
- checkPrivilege(privilege.name()),
- "This privilege %s is not support in the Ranger hive authorization",
- privilege.name());
- });
+ privilege ->
+ check(
+ checkPrivilege(privilege.name()),
+ "This privilege %s is not support in the Ranger hive authorization",
Review Comment:
```suggestion
"This privilege %s is not supported in the Ranger hive authorization",
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724530797
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy is not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilege -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilege))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role is not exist. */
+ private RangerRole createRangerRole(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role is not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
Review Comment:
> Policies can't be null, please see
>
> ```
> // Only return the policies that are managed by Gravitino.
> if (policies.size() > 1) {
> throw new AuthorizationPluginException(
> "Each metadata object only have one Gravitino management enable policies.");
> }
> ```
OK.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#issuecomment-2301488589
> Does it support multiple Hive catalog uses one Ranger?
Yes, we support.
Because each Hive catalog have a separate AuthorizationPlugin instance.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#issuecomment-2301657509
> > > Does it support multiple Hive catalog uses one Ranger?
> >
> >
> > Yes, we support. Because each Hive catalog have a separate AuthorizationPlugin instance.
>
> All the authorization plugin uses the same label. Won't it influence each other?
They use the same property names but have different values.
The key point is `RANGER_SERVICE_NAME` has different values.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1723051516
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
Review Comment:
1. Ranger only support use `policyFilterKeys` to search policy, get fuzzy results.
2. and, we can use `policyPreciseFilterKeys` to Precise Filter in the result. we can get Precise results.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724752624
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,583 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.authorization.ranger.reference.VXGroup;
+import org.apache.gravitino.authorization.ranger.reference.VXGroupList;
+import org.apache.gravitino.authorization.ranger.reference.VXUser;
+import org.apache.gravitino.authorization.ranger.reference.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Ranger authorization operations plugin abstract class. <br>
+ * 1. For Ranger limit, The same metadata object only has a unique Ranger policy, So a Ranger policy
+ * maybe contains multiple Gravitino securable objects. <br>
+ * 2. For easy management, each Ranger privilege will create one RangerPolicyItemAccess in the
+ * policy. <br>
+ * 3. Ranger also have Role concept, and support adds multiple users or groups in the Ranger Role,
+ * So we can use the Ranger Role to implement the Gravitino Role. <br>
+ * 4. The Ranger policy also supports multiple users and groups, But we only use a user or group to
+ * implement Gravitino Owner concept. <br>
+ */
+public class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected String rangerServiceName;
+ protected RangerClientExtend rangerClient;
+ private RangerHelper rangerHelper;
+ @VisibleForTesting public final String rangerAdminName;
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ rangerAdminName = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ RangerHelper.check(rangerUrl != null, "Ranger admin URL is required");
+ RangerHelper.check(authType != null, "Ranger auth type is required");
+ RangerHelper.check(rangerAdminName != null, "Ranger username is required");
+ RangerHelper.check(password != null, "Ranger password is required");
+ RangerHelper.check(rangerServiceName != null, "Ranger service name is required");
+ rangerClient = new RangerClientExtend(rangerUrl, authType, rangerAdminName, password);
+ rangerHelper = new RangerHelper(this, catalogProvider);
+ }
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return rangerHelper.privilegesMapping.get(name);
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(rangerHelper.ownerPrivileges);
+ }
+
+ /**
+ * Create a new role in the Ranger. <br>
+ * 1. Create a policy for metadata object. <br>
+ * 2. Save role name in the Policy items. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ return rangerHelper.checkRangerRole(role.name());
+ }
+
+ /** Remove the role name from the Ranger policy item, and delete this Role in the Ranger. <br> */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, delete the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), rangerAdminName, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult = doRemoveSecurableObject((RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult = doUpdateSecurableObject((RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ * 1. If the metadata object already has an owner, then transfer the ownership from preOwner to
+ * newOwner, The function params preOwner and newOwner don't equal null. <br>
+ * 2. If the metadata object doesn't have an owner, then set the owner to newOwner, The function
+ * params preOwner equal null and newOwner don't equal null. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object.
+ * @param newOwner The new owner of the metadata object.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ RangerHelper.check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = rangerHelper.findManagedPolicy(metadataObject);
+ try {
+ if (policy == null) {
+ policy = rangerHelper.addOwnerToNewPolicy(metadataObject, newOwner);
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerHelper.updatePolicyOwner(policy, preOwner, newOwner);
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this user to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param user The user to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role: {} to user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this user from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param user The user to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this group to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Grant role: {} to group: {} failed!", role, group, e);
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this group from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param group The group to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from group: {} failed!", role, group, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
Review Comment:
```suggestion
LOG.warn("The user({}) already exists in the Ranger!", user.name());
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724205839
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ mapAccesses.put(access.getType(), true);
+ });
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy exists but has different privileges, also return true. Because one Ranger
+ * policy maybe contain multiple Gravitino securable object <br>
+ * 4. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravition securable object's privilege
+ // and roleName
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If exist policy and have same privilege then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(change.getSecurableObject().fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(
+ SecurableObjects.DOT_SPLITTER.splitToList(change.getSecurableObject().fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+ }
+
+ addPolicyItem(policy, change.getRoleName(), change.getSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return true;
+ }
+
+ /**
+ * Remove the securable object's privilege from the policy. <br>
+ * Because Ranger use unique metadata to location Ranger policy and manage the all privileges, So
+ * one Ranger policy maybe contain multiple Gravitino privilege objects. <br>
+ * Remove Ranger policy item condition is: <br>
+ * 1. This Ranger policy item's accesses equal the Gravition securable object's privilege. <br>
+ * 2. This Ranger policy item's users and groups is empty. <br>
+ * If policy didn't have any policy item, then delete this policy: <br>
+ */
+ private boolean doRemoveSecurableObject(
+ String roleName, RoleChange.RemoveSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ policy
+ .getPolicyItems()
+ .forEach(
+ policyItem -> {
+ boolean match =
+ policyItem.getAccesses().stream()
+ .allMatch(
+ // Find the policy item that match access and role
+ access -> {
+ // Use Gravitino privilege to search the Ranger policy item's access
+ boolean matchPrivilege =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(
+ privilege ->
+ translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .anyMatch(privilege -> privilege.equals(access.getType()));
+ return matchPrivilege;
+ });
+ if (match) {
+ policyItem.getRoles().removeIf(roleName::equals);
+ }
+ });
+
+ // If the policy does have any role and user and group, then remove it.
+ policy
+ .getPolicyItems()
+ .removeIf(
+ policyItem ->
+ policyItem.getRoles().isEmpty()
+ && policyItem.getUsers().isEmpty()
+ && policyItem.getGroups().isEmpty());
+
+ try {
+ if (policy.getPolicyItems().size() == 0) {
+ rangerClient.deletePolicy(policy.getId());
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ LOG.error("Failed to remove the policy item from the Ranger policy {}!", policy);
+ throw new RuntimeException(e);
+ }
+ } else {
+ LOG.warn(
+ "Cannot find the Ranger policy({}) for the Gravitino securable object({})!",
+ roleName,
+ change.getSecurableObject().fullName());
+ // Don't throw exception or return false, because need support immutable operation.
+ }
+ return true;
+ }
+
+ /**
+ * 1. Find the policy base securable object. <br>
+ * 2. If the policy is exist, then user new securable object's privilege to update. <br>
+ * 3. If the policy is not exist return false. <br>
+ */
+ private boolean doUpdateSecurableObject(
+ String roleName, RoleChange.UpdateSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ removePolicyItem(policy, roleName, change.getSecurableObject());
+ addPolicyItem(policy, roleName, change.getNewSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ } else {
+ LOG.warn(
+ "Cannot find the policy({}) for the securable object({})!",
+ roleName,
+ change.getSecurableObject().fullName());
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Add policy item access items base the securable object's privileges. <br>
+ * We didn't clean the policy items, because one Ranger policy maybe contain multiple Gravitino
+ * securable objects. <br>
+ */
+ private void addPolicyItem(
+ RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkSecurableObject(securableObject);
+
+ // Add the policy items by the securable object's privileges
+ securableObject
+ .privileges()
+ .forEach(
+ gravitinoPrivilege -> {
+ // Translate the Gravitino privilege to map Ranger privilege
+ translatePrivilege(gravitinoPrivilege.name())
+ .forEach(
+ mappedPrivilege -> {
+ // Find the policy item that matches Gravitino privilege
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItems =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ access -> access.getType().equals(mappedPrivilege));
+ })
+ .collect(Collectors.toList());
+
Review Comment:
You need add a `TODO` at least.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724331813
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have a Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contains multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
Review Comment:
// Because Ranger only supports search the policies by key words, the results will contain many unnecessary data.
// For example, you search table1, Ranger return table1, table12, table13. RangerAuthorization should filter inaccurate data by hand.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724546784
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,998 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have a Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contains multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Grant role: {} to group: {} failed!", role, group, e);
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from group: {} failed!", role, group, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users =
+ StringUtils.isEmpty(userName) ? Sets.newHashSet() : Sets.newHashSet(userName);
+ Set<String> groups =
+ StringUtils.isEmpty(groupName) ? Sets.newHashSet() : Sets.newHashSet(groupName);
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(Sets.newHashSet(roleName));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception, if the role does not exist, we will then create it.
+ LOG.warn("The role({}) is not exist in the Ranger!", roleName);
+ }
+
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manually precisely filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are managed by Gravitino.
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ mapAccesses.put(access.getType(), true);
+ });
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy exists but has different privileges, also return true. Because one Ranger
+ * policy maybe contain multiple Gravitino securable object <br>
+ * 4. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravitino securable object's privilege
+ // and roleName
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If it exists policy with the same privilege, then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(change.getSecurableObject().fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(
+ SecurableObjects.DOT_SPLITTER.splitToList(change.getSecurableObject().fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ List<String> rangerDefinesList =
+ Lists.newArrayList(
+ RangerDefines.RESOURCE_DATABASE,
+ RangerDefines.RESOURCE_TABLE,
+ RangerDefines.RESOURCE_COLUMN);
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy.getResources().put(rangerDefinesList.get(i), policyResource);
+ }
+ }
+
+ addPolicyItem(policy, change.getRoleName(), change.getSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return true;
+ }
+
+ /**
+ * Remove the securable object's privilege from the policy. <br>
+ * Because Ranger uses unique metadata to location Ranger policy and manages all the privileges,
+ * So A Ranger policy maybe contains multiple Gravitino privilege objects. <br>
+ * Remove Ranger policy item condition is: <br>
+ * 1. This Ranger policy item's accesses are equal the Gravitino securable object's privilege.
+ * <br>
+ * 2. This Ranger policy item's users and groups are empty. <br>
+ * If policy didn't have any policy item, then delete this policy: <br>
+ */
+ private boolean doRemoveSecurableObject(
+ String roleName, RoleChange.RemoveSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy == null) {
+ LOG.warn(
+ "Cannot find the Ranger policy({}) for the Gravitino securable object({})!",
+ roleName,
+ change.getSecurableObject().fullName());
+ // Don't throw exception or return false, because need support immutable operation.
+ return true;
+ }
+
+ List<RangerPolicyItem> policyItems = policy.getPolicyItems();
+ policyItems.forEach(
+ policyItem -> {
+ boolean match =
Review Comment:
Maybe we can extract this to a method to let other update/remove/add securable object method to reuse it?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#issuecomment-2302034040
> Only one point:
>
> 1. Some privileges like `use schema`, `use catalog`, `create catalog` could be pushed down underlying system, too. The check logic will throw exception for them.
I created EPIC https://github.com/apache/gravitino/pull/4515 to track these issue.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724962022
##########
authorizations/authorization-ranger/src/test/java/org/apache/gravitino/authorization/ranger/integration/test/RangerITEnv.java:
##########
@@ -252,7 +257,7 @@ protected static String updateOrCreateRangerPolicy(
if (!policies.isEmpty()) {
// Because Ranger user the wildcard filter, Ranger will return the policy meets
// the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
Review Comment:
DONE
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHelper.java:
##########
@@ -0,0 +1,533 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This class is a helper class for the Ranger authorization plugin. It provides the ability to
+ * manage the Ranger policies and roles.
+ */
+public class RangerHelper {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerHelper.class);
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ RangerAuthorizationPlugin rangerAuthorizationPlugin;
+
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ /** The owner privileges, the owner can do anything on the metadata object */
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise search, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, If you use `db.table` condition to search policy, the Ranger will
+ * match `db1.table1`, `db1.table2`, `db*.table*`, So we need to manually precisely filter this
+ * research results. <br>
+ * policySearchKeys: The search Ranger policy condition key defines. <br>
+ * policyPreciseFilterKeys: The precise filter Ranger search results key defines <br>
+ */
+ protected List<String> policySearchKeys = null;
+
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public RangerHelper(RangerAuthorizationPlugin rangerAuthorizationPlugin, String catalogProvider) {
+ this.rangerAuthorizationPlugin = rangerAuthorizationPlugin;
+ switch (catalogProvider) {
+ case "hive":
+ initPrivilegesMapping();
+ initOwnerPrivileges();
+ initPolicySearchKeys();
+ initPreciseFilterKeys();
+ break;
+ default:
+ throw new IllegalArgumentException(
+ "Authorization plugin unsupported catalog provider: " + catalogProvider);
+ }
+ }
+
+ /** Initial mapping Gravitino privilege name to the underlying authorization system privileges. */
+ private void initPrivilegesMapping() {
+ privilegesMapping =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.MODIFY_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_UPDATE,
+ RangerDefines.ACCESS_TYPE_HIVE_ALTER,
+ RangerDefines.ACCESS_TYPE_HIVE_WRITE))
+ .put(
+ Privilege.Name.SELECT_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_READ, RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .build();
+ }
+
+ /** Initial Owner privileges */
+ private void initOwnerPrivileges() {
+ ownerPrivileges = ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_ALL);
+ }
+
+ /** Initial Ranger policy search key defines */
+ private void initPolicySearchKeys() {
+ policySearchKeys =
+ Arrays.asList(
+ RangerDefines.SEARCH_FILTER_DATABASE,
+ RangerDefines.SEARCH_FILTER_TABLE,
+ RangerDefines.SEARCH_FILTER_COLUMN);
+ }
+
+ /** Initial precise filter key defines */
+ private void initPreciseFilterKeys() {
+ policyPreciseFilterKeys =
+ Arrays.asList(
+ RangerDefines.RESOURCE_DATABASE,
+ RangerDefines.RESOURCE_TABLE,
+ RangerDefines.RESOURCE_COLUMN);
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Set<String> setAccesses = new HashSet<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (setAccesses.contains(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ setAccesses.add(access.getType());
+ });
+ }
+
+ /**
+ * Add policy item access items base the securable object's privileges. <br>
+ * We cannot clean the policy items because one Ranger policy maybe contains multiple Gravitino
+ * securable objects. <br>
+ */
+ void addPolicyItem(RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkPrivileges(securableObject);
+
+ // Add the policy items by the securable object's privileges
+ securableObject
+ .privileges()
+ .forEach(
+ gravitinoPrivilege -> {
+ // Translate the Gravitino privilege to map Ranger privilege
+ rangerAuthorizationPlugin
+ .translatePrivilege(gravitinoPrivilege.name())
+ .forEach(
+ mappedPrivilege -> {
+ // Find the policy item that matches Gravitino privilege
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItems =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ access -> access.getType().equals(mappedPrivilege));
+ })
+ .collect(Collectors.toList());
+
+ if (matchPolicyItems.size() == 0) {
+ // If the policy item does not exist, then create a new policy item
+ RangerPolicy.RangerPolicyItem policyItem =
+ new RangerPolicy.RangerPolicyItem();
+ RangerPolicy.RangerPolicyItemAccess access =
+ new RangerPolicy.RangerPolicyItemAccess();
+ access.setType(mappedPrivilege);
+ policyItem.getAccesses().add(access);
+ policyItem.getRoles().add(roleName);
+ if (Privilege.Condition.ALLOW == gravitinoPrivilege.condition()) {
+ policy.getPolicyItems().add(policyItem);
+ } else {
+ policy.getDenyPolicyItems().add(policyItem);
+ }
+ } else {
+ // If the policy item exists, then add the role to the policy item
+ matchPolicyItems.stream()
+ .forEach(
+ policyItem -> {
+ // If the role is not in the policy item, then add it
+ if (!policyItem.getRoles().contains(roleName)) {
+ policyItem.getRoles().add(roleName);
+ }
+ });
+ }
+ });
+ });
+ }
+
+ /**
+ * Remove policy item base the securable object's privileges and role name. <br>
+ * We cannot directly clean the policy items because one Ranger policy maybe contains multiple
+ * Gravitino privilege objects. <br>
+ */
+ void removePolicyItem(RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkPrivileges(securableObject);
+
+ // Delete the policy role base the securable object's privileges
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ boolean matchPrivilege =
+ securableObject.privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(
+ privilege ->
+ rangerAuthorizationPlugin
+ .translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .anyMatch(
+ privilege -> {
+ return access.getType().equals(privilege);
+ });
+ if (matchPrivilege
+ && !policyItem.getUsers().isEmpty()
Review Comment:
We can only remove this policy item if there are no users or groups
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,583 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.authorization.ranger.reference.VXGroup;
+import org.apache.gravitino.authorization.ranger.reference.VXGroupList;
+import org.apache.gravitino.authorization.ranger.reference.VXUser;
+import org.apache.gravitino.authorization.ranger.reference.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Ranger authorization operations plugin abstract class. <br>
+ * 1. For Ranger limit, The same metadata object only has a unique Ranger policy, So a Ranger policy
+ * maybe contains multiple Gravitino securable objects. <br>
+ * 2. For easy management, each Ranger privilege will create one RangerPolicyItemAccess in the
+ * policy. <br>
+ * 3. Ranger also have Role concept, and support adds multiple users or groups in the Ranger Role,
+ * So we can use the Ranger Role to implement the Gravitino Role. <br>
+ * 4. The Ranger policy also supports multiple users and groups, But we only use a user or group to
+ * implement Gravitino Owner concept. <br>
+ */
+public class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected String rangerServiceName;
+ protected RangerClientExtend rangerClient;
+ private RangerHelper rangerHelper;
+ @VisibleForTesting public final String rangerAdminName;
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ rangerAdminName = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ RangerHelper.check(rangerUrl != null, "Ranger admin URL is required");
+ RangerHelper.check(authType != null, "Ranger auth type is required");
+ RangerHelper.check(rangerAdminName != null, "Ranger username is required");
+ RangerHelper.check(password != null, "Ranger password is required");
+ RangerHelper.check(rangerServiceName != null, "Ranger service name is required");
+ rangerClient = new RangerClientExtend(rangerUrl, authType, rangerAdminName, password);
+ rangerHelper = new RangerHelper(this, catalogProvider);
+ }
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return rangerHelper.privilegesMapping.get(name);
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(rangerHelper.ownerPrivileges);
+ }
+
+ /**
+ * Create a new role in the Ranger. <br>
+ * 1. Create a policy for metadata object. <br>
+ * 2. Save role name in the Policy items. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ return rangerHelper.checkRangerRole(role.name());
+ }
+
+ /** Remove the role name from the Ranger policy item, and delete this Role in the Ranger. <br> */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, delete the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), rangerAdminName, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult = doRemoveSecurableObject((RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult = doUpdateSecurableObject((RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ * 1. If the metadata object already has an owner, then transfer the ownership from preOwner to
+ * newOwner, The function params preOwner and newOwner don't equal null. <br>
+ * 2. If the metadata object doesn't have an owner, then set the owner to newOwner, The function
+ * params preOwner equal null and newOwner don't equal null. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object.
+ * @param newOwner The new owner of the metadata object.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ RangerHelper.check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = rangerHelper.findManagedPolicy(metadataObject);
+ try {
+ if (policy == null) {
+ policy = rangerHelper.addOwnerToNewPolicy(metadataObject, newOwner);
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerHelper.updatePolicyOwner(policy, preOwner, newOwner);
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this user to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param user The user to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role: {} to user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this user from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param user The user to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this group to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Grant role: {} to group: {} failed!", role, group, e);
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this group from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param group The group to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from group: {} failed!", role, group, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) already exists in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) doesn't exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) doesn't exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) doesn't exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) doesn't exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Add the securable object's privilege to the Ranger policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = rangerHelper.findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravitino securable object's privilege
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If it exists policy with the same privilege, then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(change.getSecurableObject().fullName());
+ policy.setPolicyLabels(Lists.newArrayList(RangerHelper.MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
Review Comment:
DONE
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,583 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.authorization.ranger.reference.VXGroup;
+import org.apache.gravitino.authorization.ranger.reference.VXGroupList;
+import org.apache.gravitino.authorization.ranger.reference.VXUser;
+import org.apache.gravitino.authorization.ranger.reference.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Ranger authorization operations plugin abstract class. <br>
+ * 1. For Ranger limit, The same metadata object only has a unique Ranger policy, So a Ranger policy
+ * maybe contains multiple Gravitino securable objects. <br>
+ * 2. For easy management, each Ranger privilege will create one RangerPolicyItemAccess in the
+ * policy. <br>
+ * 3. Ranger also have Role concept, and support adds multiple users or groups in the Ranger Role,
+ * So we can use the Ranger Role to implement the Gravitino Role. <br>
+ * 4. The Ranger policy also supports multiple users and groups, But we only use a user or group to
+ * implement Gravitino Owner concept. <br>
+ */
+public class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected String rangerServiceName;
+ protected RangerClientExtend rangerClient;
+ private RangerHelper rangerHelper;
+ @VisibleForTesting public final String rangerAdminName;
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ rangerAdminName = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ RangerHelper.check(rangerUrl != null, "Ranger admin URL is required");
+ RangerHelper.check(authType != null, "Ranger auth type is required");
+ RangerHelper.check(rangerAdminName != null, "Ranger username is required");
+ RangerHelper.check(password != null, "Ranger password is required");
+ RangerHelper.check(rangerServiceName != null, "Ranger service name is required");
+ rangerClient = new RangerClientExtend(rangerUrl, authType, rangerAdminName, password);
+ rangerHelper = new RangerHelper(this, catalogProvider);
+ }
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return rangerHelper.privilegesMapping.get(name);
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(rangerHelper.ownerPrivileges);
+ }
+
+ /**
+ * Create a new role in the Ranger. <br>
+ * 1. Create a policy for metadata object. <br>
+ * 2. Save role name in the Policy items. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ return rangerHelper.checkRangerRole(role.name());
+ }
+
+ /** Remove the role name from the Ranger policy item, and delete this Role in the Ranger. <br> */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, delete the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), rangerAdminName, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult = doRemoveSecurableObject((RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult = doUpdateSecurableObject((RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ * 1. If the metadata object already has an owner, then transfer the ownership from preOwner to
+ * newOwner, The function params preOwner and newOwner don't equal null. <br>
+ * 2. If the metadata object doesn't have an owner, then set the owner to newOwner, The function
+ * params preOwner equal null and newOwner don't equal null. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object.
+ * @param newOwner The new owner of the metadata object.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ RangerHelper.check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = rangerHelper.findManagedPolicy(metadataObject);
+ try {
+ if (policy == null) {
+ policy = rangerHelper.addOwnerToNewPolicy(metadataObject, newOwner);
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerHelper.updatePolicyOwner(policy, preOwner, newOwner);
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this user to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param user The user to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role: {} to user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this user from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param user The user to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this group to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Grant role: {} to group: {} failed!", role, group, e);
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this group from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param group The group to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from group: {} failed!", role, group, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) already exists in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) doesn't exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) doesn't exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) doesn't exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) doesn't exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Add the securable object's privilege to the Ranger policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = rangerHelper.findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravitino securable object's privilege
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If it exists policy with the same privilege, then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(change.getSecurableObject().fullName());
+ policy.setPolicyLabels(Lists.newArrayList(RangerHelper.MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(
+ SecurableObjects.DOT_SPLITTER.splitToList(change.getSecurableObject().fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ List<String> rangerDefinesList =
+ Lists.newArrayList(
+ RangerDefines.RESOURCE_DATABASE,
+ RangerDefines.RESOURCE_TABLE,
+ RangerDefines.RESOURCE_COLUMN);
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy.getResources().put(rangerDefinesList.get(i), policyResource);
+ }
+ }
+
+ rangerHelper.addPolicyItem(policy, change.getRoleName(), change.getSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return true;
+ }
+
+ /**
+ * Remove the securable object's privilege from the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, then remove role name in the policy items.
+ * <br>
+ * 3. If policy does not contain any policy item, then delete this policy. <br>
+ */
+ private boolean doRemoveSecurableObject(RoleChange.RemoveSecurableObject change) {
+ RangerPolicy policy = rangerHelper.findManagedPolicy(change.getSecurableObject());
+ if (policy == null) {
+ LOG.warn(
+ "Cannot find the Ranger policy({}) for the Gravitino securable object({})!",
+ change.getRoleName(),
+ change.getSecurableObject().fullName());
+ // Don't throw exception or return false, because need support immutable operation.
+ return true;
+ }
+
+ policy
+ .getPolicyItems()
+ .forEach(
+ policyItem -> {
+ boolean match =
+ policyItem.getAccesses().stream()
+ .allMatch(
+ // Find the policy item that matches access and role
+ access -> {
+ // Use Gravitino privilege to search the Ranger policy item's access
+ boolean matchPrivilege =
Review Comment:
They have different logic
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHelper.java:
##########
@@ -0,0 +1,533 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This class is a helper class for the Ranger authorization plugin. It provides the ability to
+ * manage the Ranger policies and roles.
+ */
+public class RangerHelper {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerHelper.class);
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ RangerAuthorizationPlugin rangerAuthorizationPlugin;
+
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ /** The owner privileges, the owner can do anything on the metadata object */
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise search, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, If you use `db.table` condition to search policy, the Ranger will
+ * match `db1.table1`, `db1.table2`, `db*.table*`, So we need to manually precisely filter this
+ * research results. <br>
+ * policySearchKeys: The search Ranger policy condition key defines. <br>
+ * policyPreciseFilterKeys: The precise filter Ranger search results key defines <br>
+ */
+ protected List<String> policySearchKeys = null;
+
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public RangerHelper(RangerAuthorizationPlugin rangerAuthorizationPlugin, String catalogProvider) {
+ this.rangerAuthorizationPlugin = rangerAuthorizationPlugin;
+ switch (catalogProvider) {
+ case "hive":
+ initPrivilegesMapping();
+ initOwnerPrivileges();
+ initPolicySearchKeys();
+ initPreciseFilterKeys();
+ break;
+ default:
+ throw new IllegalArgumentException(
+ "Authorization plugin unsupported catalog provider: " + catalogProvider);
+ }
+ }
+
+ /** Initial mapping Gravitino privilege name to the underlying authorization system privileges. */
+ private void initPrivilegesMapping() {
+ privilegesMapping =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.MODIFY_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_UPDATE,
+ RangerDefines.ACCESS_TYPE_HIVE_ALTER,
+ RangerDefines.ACCESS_TYPE_HIVE_WRITE))
+ .put(
+ Privilege.Name.SELECT_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_READ, RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .build();
+ }
+
+ /** Initial Owner privileges */
+ private void initOwnerPrivileges() {
+ ownerPrivileges = ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_ALL);
+ }
+
+ /** Initial Ranger policy search key defines */
+ private void initPolicySearchKeys() {
+ policySearchKeys =
+ Arrays.asList(
+ RangerDefines.SEARCH_FILTER_DATABASE,
+ RangerDefines.SEARCH_FILTER_TABLE,
+ RangerDefines.SEARCH_FILTER_COLUMN);
+ }
+
+ /** Initial precise filter key defines */
+ private void initPreciseFilterKeys() {
+ policyPreciseFilterKeys =
+ Arrays.asList(
+ RangerDefines.RESOURCE_DATABASE,
+ RangerDefines.RESOURCE_TABLE,
+ RangerDefines.RESOURCE_COLUMN);
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Set<String> setAccesses = new HashSet<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (setAccesses.contains(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ setAccesses.add(access.getType());
+ });
+ }
+
+ /**
+ * Add policy item access items base the securable object's privileges. <br>
+ * We cannot clean the policy items because one Ranger policy maybe contains multiple Gravitino
+ * securable objects. <br>
+ */
+ void addPolicyItem(RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkPrivileges(securableObject);
+
+ // Add the policy items by the securable object's privileges
+ securableObject
+ .privileges()
+ .forEach(
+ gravitinoPrivilege -> {
+ // Translate the Gravitino privilege to map Ranger privilege
+ rangerAuthorizationPlugin
+ .translatePrivilege(gravitinoPrivilege.name())
+ .forEach(
+ mappedPrivilege -> {
+ // Find the policy item that matches Gravitino privilege
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItems =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ access -> access.getType().equals(mappedPrivilege));
+ })
+ .collect(Collectors.toList());
+
+ if (matchPolicyItems.size() == 0) {
+ // If the policy item does not exist, then create a new policy item
+ RangerPolicy.RangerPolicyItem policyItem =
+ new RangerPolicy.RangerPolicyItem();
+ RangerPolicy.RangerPolicyItemAccess access =
+ new RangerPolicy.RangerPolicyItemAccess();
+ access.setType(mappedPrivilege);
+ policyItem.getAccesses().add(access);
+ policyItem.getRoles().add(roleName);
+ if (Privilege.Condition.ALLOW == gravitinoPrivilege.condition()) {
+ policy.getPolicyItems().add(policyItem);
+ } else {
+ policy.getDenyPolicyItems().add(policyItem);
+ }
+ } else {
+ // If the policy item exists, then add the role to the policy item
+ matchPolicyItems.stream()
+ .forEach(
+ policyItem -> {
+ // If the role is not in the policy item, then add it
+ if (!policyItem.getRoles().contains(roleName)) {
+ policyItem.getRoles().add(roleName);
+ }
+ });
+ }
+ });
+ });
+ }
+
+ /**
+ * Remove policy item base the securable object's privileges and role name. <br>
+ * We cannot directly clean the policy items because one Ranger policy maybe contains multiple
+ * Gravitino privilege objects. <br>
+ */
+ void removePolicyItem(RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkPrivileges(securableObject);
+
+ // Delete the policy role base the securable object's privileges
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ boolean matchPrivilege =
+ securableObject.privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(
+ privilege ->
+ rangerAuthorizationPlugin
+ .translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .anyMatch(
+ privilege -> {
+ return access.getType().equals(privilege);
+ });
+ if (matchPrivilege
+ && !policyItem.getUsers().isEmpty()
+ && !policyItem.getGroups().isEmpty()) {
+ // Not ownership policy item, then remove the role
+ policyItem.getRoles().removeIf(roleName::equals);
+ }
+ });
+ });
+
+ // Delete the policy items if the roles are empty and not ownership policy item
+ policy
+ .getPolicyItems()
+ .removeIf(
+ policyItem -> {
+ return policyItem.getRoles().isEmpty()
+ && policyItem.getUsers().isEmpty()
+ && policyItem.getGroups().isEmpty();
+ });
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param securableObject The securable object to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ private boolean checkPrivileges(SecurableObject securableObject) {
+ securableObject
+ .privileges()
+ .forEach(
+ privilege -> {
+ check(
+ privilegesMapping.containsKey(privilege.name()),
+ "This privilege %s is not supported in the Ranger hive authorization",
+ privilege.name());
+ });
+ return true;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(
+ RangerDefines.SEARCH_FILTER_SERVICE_NAME, rangerAuthorizationPlugin.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policySearchKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies =
+ rangerAuthorizationPlugin.rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ /**
+ * Because Ranger doesn't support the precise search, Ranger will return the policy meets
+ * the wildcard(*,?) conditions, If you use `db.table` condition to search policy, the
+ * Ranger will match `db1.table1`, `db1.table2`, `db*.table*`, So we need to manually
+ * precisely filter this research results.
+ */
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are managed by Gravitino.
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
Review Comment:
DONE
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,556 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.reference.VXGroup;
+import org.apache.gravitino.authorization.ranger.reference.VXGroupList;
+import org.apache.gravitino.authorization.ranger.reference.VXUser;
+import org.apache.gravitino.authorization.ranger.reference.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Ranger authorization operations plugin abstract class. <br>
+ * 1. For Ranger limit, The same metadata object only has a unique Ranger policy, So a Ranger policy
+ * maybe contains multiple Gravitino securable objects. <br>
+ * 2. For easy management, each Ranger privilege will create one RangerPolicyItemAccess in the
+ * policy. <br>
+ * 3. Ranger also have Role concept, and support adds multiple users or groups in the Ranger Role,
+ * So we can use the Ranger Role to implement the Gravitino Role. <br>
+ * 4. The Ranger policy also supports multiple users and groups, But we only use a user or group to
+ * implement Gravitino Owner concept. <br>
+ */
+public class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected String rangerServiceName;
+ protected RangerClientExtend rangerClient;
+ private RangerHelper rangerHelper;
+ @VisibleForTesting public final String rangerAdminName;
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ rangerAdminName = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ RangerHelper.check(rangerUrl != null, "Ranger admin URL is required");
+ RangerHelper.check(authType != null, "Ranger auth type is required");
+ RangerHelper.check(rangerAdminName != null, "Ranger username is required");
+ RangerHelper.check(password != null, "Ranger password is required");
+ RangerHelper.check(rangerServiceName != null, "Ranger service name is required");
+ rangerClient = new RangerClientExtend(rangerUrl, authType, rangerAdminName, password);
+ rangerHelper = new RangerHelper(this, catalogProvider);
+ }
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return rangerHelper.privilegesMapping.get(name);
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(rangerHelper.ownerPrivileges);
+ }
+
+ /**
+ * Create a new role in the Ranger. <br>
+ * 1. Create a policy for metadata object. <br>
+ * 2. Save role name in the Policy items. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ return rangerHelper.checkRangerRole(role.name());
+ }
+
+ /** Remove the role name from the Ranger policy item, and delete this Role in the Ranger. <br> */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, delete the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), rangerAdminName, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult = doRemoveSecurableObject((RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult = doUpdateSecurableObject((RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ * 1. If the metadata object already has an owner, then transfer the ownership from preOwner to
+ * newOwner, The function params preOwner and newOwner don't equal null. <br>
+ * 2. If the metadata object doesn't have an owner, then set the owner to newOwner, The function
+ * params preOwner equal null and newOwner don't equal null. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object.
+ * @param newOwner The new owner of the metadata object.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ RangerHelper.check(newOwner != null, "The newOwner must be not null");
+
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+
+ RangerPolicy policy = rangerHelper.findManagedPolicy(metadataObject);
+ try {
+ if (policy == null) {
+ policy = rangerHelper.addOwnerToNewPolicy(metadataObject, newOwner);
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerHelper.updatePolicyOwner(policy, preOwner, newOwner);
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this user to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param user The user to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role: {} to user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this user from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param user The user to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this group to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Grant role: {} to group: {} failed!", role, group, e);
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this group from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param group The group to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from group: {} failed!", role, group, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) already exists in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) doesn't exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) doesn't exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) doesn't exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) doesn't exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Add the securable object's privilege to the Ranger policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = rangerHelper.findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravitino securable object's privilege
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If it exists policy with the same privilege, then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = rangerHelper.createPolicyAddResources(change.getSecurableObject());
+ }
+
+ rangerHelper.addPolicyItem(policy, change.getRoleName(), change.getSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return true;
+ }
+
+ /**
+ * Remove the securable object's privilege from the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, then remove role name in the policy items.
+ * <br>
+ * 3. If policy does not contain any policy item, then delete this policy. <br>
+ */
+ private boolean doRemoveSecurableObject(RoleChange.RemoveSecurableObject change) {
+ RangerPolicy policy = rangerHelper.findManagedPolicy(change.getSecurableObject());
+ if (policy == null) {
+ LOG.warn(
+ "Cannot find the Ranger policy({}) for the Gravitino securable object({})!",
+ change.getRoleName(),
+ change.getSecurableObject().fullName());
+ // Don't throw exception or return false, because need support immutable operation.
+ return true;
+ }
+
+ policy
+ .getPolicyItems()
+ .forEach(
+ policyItem -> {
+ boolean match =
+ policyItem.getAccesses().stream()
+ .allMatch(
+ // Find the policy item that matches access and role
+ access -> {
+ // Use Gravitino privilege to search the Ranger policy item's access
+ boolean matchPrivilege =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(
+ privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .anyMatch(privilege -> privilege.equals(access.getType()));
+ return matchPrivilege;
+ });
+ if (match) {
+ policyItem.getRoles().removeIf(change.getRoleName()::equals);
+ }
+ });
+
+ // If the policy does have any role and user and group, then remove it.
+ policy
+ .getPolicyItems()
+ .removeIf(
+ policyItem ->
+ policyItem.getRoles().isEmpty()
+ && policyItem.getUsers().isEmpty()
+ && policyItem.getGroups().isEmpty());
+
+ try {
+ if (policy.getPolicyItems().size() == 0) {
+ rangerClient.deletePolicy(policy.getId());
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ LOG.error("Failed to remove the policy item from the Ranger policy {}!", policy);
+ throw new RuntimeException(e);
+ }
+ return true;
+ }
+
+ /**
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists, then user new securable object's privilege to update. <br>
+ * 3. If the policy does not exist, return false. <br>
+ */
+ private boolean doUpdateSecurableObject(RoleChange.UpdateSecurableObject change) {
+ RangerPolicy policy = rangerHelper.findManagedPolicy(change.getSecurableObject());
+ if (policy == null) {
+ LOG.warn(
+ "Cannot find the Ranger policy({}) for the Gravitino securable object({})!",
+ change.getRoleName(),
+ change.getSecurableObject().fullName());
+ // Don't throw exception or return false, because need support immutable operation.
+ return false;
+ }
+
+ rangerHelper.removePolicyItem(policy, change.getRoleName(), change.getSecurableObject());
+ rangerHelper.addPolicyItem(policy, change.getRoleName(), change.getNewSecurableObject());
+ try {
+ if (policy.getId() == null) {
Review Comment:
Yes, Because this ID is LONG type.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,583 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.authorization.ranger.reference.VXGroup;
+import org.apache.gravitino.authorization.ranger.reference.VXGroupList;
+import org.apache.gravitino.authorization.ranger.reference.VXUser;
+import org.apache.gravitino.authorization.ranger.reference.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Ranger authorization operations plugin abstract class. <br>
+ * 1. For Ranger limit, The same metadata object only has a unique Ranger policy, So a Ranger policy
+ * maybe contains multiple Gravitino securable objects. <br>
+ * 2. For easy management, each Ranger privilege will create one RangerPolicyItemAccess in the
+ * policy. <br>
+ * 3. Ranger also have Role concept, and support adds multiple users or groups in the Ranger Role,
+ * So we can use the Ranger Role to implement the Gravitino Role. <br>
+ * 4. The Ranger policy also supports multiple users and groups, But we only use a user or group to
+ * implement Gravitino Owner concept. <br>
+ */
+public class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected String rangerServiceName;
+ protected RangerClientExtend rangerClient;
+ private RangerHelper rangerHelper;
+ @VisibleForTesting public final String rangerAdminName;
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ rangerAdminName = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ RangerHelper.check(rangerUrl != null, "Ranger admin URL is required");
+ RangerHelper.check(authType != null, "Ranger auth type is required");
+ RangerHelper.check(rangerAdminName != null, "Ranger username is required");
+ RangerHelper.check(password != null, "Ranger password is required");
+ RangerHelper.check(rangerServiceName != null, "Ranger service name is required");
+ rangerClient = new RangerClientExtend(rangerUrl, authType, rangerAdminName, password);
+ rangerHelper = new RangerHelper(this, catalogProvider);
+ }
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return rangerHelper.privilegesMapping.get(name);
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(rangerHelper.ownerPrivileges);
+ }
+
+ /**
+ * Create a new role in the Ranger. <br>
+ * 1. Create a policy for metadata object. <br>
+ * 2. Save role name in the Policy items. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ return rangerHelper.checkRangerRole(role.name());
+ }
+
+ /** Remove the role name from the Ranger policy item, and delete this Role in the Ranger. <br> */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, delete the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), rangerAdminName, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult = doRemoveSecurableObject((RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult = doUpdateSecurableObject((RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ * 1. If the metadata object already has an owner, then transfer the ownership from preOwner to
+ * newOwner, The function params preOwner and newOwner don't equal null. <br>
+ * 2. If the metadata object doesn't have an owner, then set the owner to newOwner, The function
+ * params preOwner equal null and newOwner don't equal null. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object.
+ * @param newOwner The new owner of the metadata object.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ RangerHelper.check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = rangerHelper.findManagedPolicy(metadataObject);
+ try {
+ if (policy == null) {
+ policy = rangerHelper.addOwnerToNewPolicy(metadataObject, newOwner);
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerHelper.updatePolicyOwner(policy, preOwner, newOwner);
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this user to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param user The user to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role: {} to user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this user from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param user The user to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this group to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Grant role: {} to group: {} failed!", role, group, e);
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this group from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param group The group to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from group: {} failed!", role, group, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) already exists in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) doesn't exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) doesn't exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) doesn't exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) doesn't exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Add the securable object's privilege to the Ranger policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = rangerHelper.findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravitino securable object's privilege
+ Set<String> policyPrivileges =
Review Comment:
They have different logic
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#issuecomment-2296236058
@yuqi1129 I fixed all problems based on your comments, Please help me review again. Thanks.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1721863651
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1015 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
Review Comment:
Yes, you are right.
I added verify whether the user exists in Ranger.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHiveAuthorizationPlugin.java:
##########
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Set;
+import org.apache.gravitino.authorization.Privilege;
+
+/**
+ * RangerHiveAuthorizationPlugin is a plugin for Apache Ranger to manage the Hive authorization of
+ * the Apache Gravitino.
+ */
+public class RangerHiveAuthorizationPlugin extends RangerAuthorizationPlugin {
+ public RangerHiveAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super(catalogProvider, config);
+ }
+
+ /**
+ * Ranger hive's privilege have `select`, `update`, `create`, `drop`, `alter`, `index`, `lock`,
+ * `read`, `write`, `repladmin`, `serviceadmin`, `refresh` and `all`. Reference:
+ * ranger/agents-common/src/main/resources/service-defs/ranger-servicedef-hive.json
+ */
+ @Override
+ protected void initMapPrivileges() {
+ mapPrivileges =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_SELECT))
Review Comment:
Sorry, This is my mistake. I already modified it.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1015 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+
+ role.securableObjects().stream()
Review Comment:
I know what you mean.
The First step is to add a user to this role. But we also need to check and add this role to the policy.
otherwise, the role may not be associated with policy item.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1015 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ // Find match policy item and set the role
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return execResult.get();
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy is not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilege -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilege))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+ return execResult.get();
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ mapAccesses.put(access.getType(), true);
+ });
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy exists but has different privileges, also return true. Because one Ranger
+ * policy maybe contain multiple Gravitino securable object <br>
+ * 4. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravition securable object's privilege
+ // and roleName
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If exist policy and have same privilege then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(change.getSecurableObject().fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(
+ SecurableObjects.DOT_SPLITTER.splitToList(change.getSecurableObject().fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+ }
+
+ addPolicyItem(policy, change.getRoleName(), change.getSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return true;
+ }
+
+ /**
+ * Remove the securable object's privilege from the policy. <br>
+ * Because Ranger use unique metadata to location Ranger policy and manage the all privileges, So
+ * one Ranger policy maybe contain multiple Gravitino privilege objects. <br>
+ * Remove Ranger policy item condition is: <br>
+ * 1. This Ranger policy item's accesses equal the Gravition securable object's privilege. <br>
+ * 2. This Ranger policy item's users and groups is empty. <br>
+ * If policy didn't have any policy item, then delete this policy: <br>
+ */
+ private boolean doRemoveSecurableObject(
+ String roleName, RoleChange.RemoveSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ policy
+ .getPolicyItems()
+ .forEach(
+ policyItem -> {
+ boolean match =
+ policyItem.getAccesses().stream()
+ .allMatch(
+ // Find the policy item that match access and role
+ access -> {
+ // Use Gravitino privilege to search the Ranger policy item's access
+ boolean matchPrivilege =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(
+ privilege ->
+ translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .anyMatch(privilege -> privilege.equals(access.getType()));
+ return matchPrivilege;
+ });
+ if (match) {
+ policyItem.getRoles().removeIf(roleName::equals);
+ }
+ });
+
+ // If the policy does have any role and user and group, then remove it.
+ policy
+ .getPolicyItems()
+ .removeIf(
+ policyItem ->
+ policyItem.getRoles().isEmpty()
+ && policyItem.getUsers().isEmpty()
+ && policyItem.getGroups().isEmpty());
+
+ try {
+ if (policy.getPolicyItems().size() == 0) {
+ rangerClient.deletePolicy(policy.getId());
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ LOG.error("Failed to remove the policy item from the Ranger policy {}!", policy);
+ throw new RuntimeException(e);
+ }
+ } else {
+ LOG.warn(
+ "Cannot find the Ranger policy({}) for the Gravitino securable object({})!",
+ roleName,
+ change.getSecurableObject().fullName());
+ // Don't throw exception or return false, because need support immutable operation.
+ }
+ return true;
+ }
+
+ /**
+ * 1. Find the policy base securable object. <br>
+ * 2. If the policy is exist, then user new securable object's privilege to update. <br>
+ * 3. If the policy is not exist return false. <br>
+ */
+ private boolean doUpdateSecurableObject(
+ String roleName, RoleChange.UpdateSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ removePolicyItem(policy, roleName, change.getSecurableObject());
+ addPolicyItem(policy, roleName, change.getNewSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ } else {
+ LOG.warn(
+ "Cannot find the policy({}) for the securable object({})!",
+ roleName,
+ change.getSecurableObject().fullName());
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Add policy item access items base the securable object's privileges. <br>
+ * We didn't clean the policy items, because one Ranger policy maybe contain multiple Gravitino
+ * securable objects. <br>
+ */
+ private void addPolicyItem(
+ RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkSecurableObject(securableObject);
+
+ // Add the policy items by the securable object's privileges
+ securableObject
+ .privileges()
+ .forEach(
+ gravitinoPrivilege -> {
+ // Translate the Gravitino privilege to mapped Ranger privilege
+ translatePrivilege(gravitinoPrivilege.name())
+ .forEach(
+ mappedPrivilege -> {
+ // Find the policy item that match access and role
+ boolean exist =
+ policy.getPolicyItems().stream()
+ .anyMatch(
+ policyItem -> {
+ return policyItem.getRoles().contains(roleName)
+ && policyItem.getAccesses().stream()
+ .anyMatch(
+ access ->
+ access.getType().equals(mappedPrivilege));
+ });
+ if (exist) {
+ return;
+ }
+
+ RangerPolicy.RangerPolicyItem policyItem =
+ new RangerPolicy.RangerPolicyItem();
+ RangerPolicy.RangerPolicyItemAccess access =
+ new RangerPolicy.RangerPolicyItemAccess();
Review Comment:
Yes, Currently one privilege has only one policy item.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHiveAuthorizationPlugin.java:
##########
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Set;
+import org.apache.gravitino.authorization.Privilege;
+
+/**
+ * RangerHiveAuthorizationPlugin is a plugin for Apache Ranger to manage the Hive authorization of
+ * the Apache Gravitino.
+ */
+public class RangerHiveAuthorizationPlugin extends RangerAuthorizationPlugin {
+ public RangerHiveAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super(catalogProvider, config);
+ }
+
+ /**
+ * Ranger hive's privilege have `select`, `update`, `create`, `drop`, `alter`, `index`, `lock`,
+ * `read`, `write`, `repladmin`, `serviceadmin`, `refresh` and `all`. Reference:
+ * ranger/agents-common/src/main/resources/service-defs/ranger-servicedef-hive.json
+ */
+ @Override
+ protected void initMapPrivileges() {
+ mapPrivileges =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
Review Comment:
These are two scenarios here:
1. If you have SecurableObjects('catalog.schema.*', CREATE_TABLE), this permission mean is you can create any table on the `catalog.schema`.
2. If you have SecurableObjects('catalog.schema.tab1', CREATE_TABLE), this permission mean is you can create table `tab1` on the `catalog.schema`.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1015 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
Review Comment:
Yes. If you create a metadata, The first step is to call `onOwnerSet(...)`, then you doesn't have a policy. In this time `onOwnerSet()` function will create a new policy to add a new policy item.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1015 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ // Find match policy item and set the role
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return execResult.get();
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
Review Comment:
Yes, you are right.
We need support idempotent operation. May be user doesn't call `grantRolesToUser` function.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1721883659
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHiveAuthorizationPlugin.java:
##########
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Set;
+import org.apache.gravitino.authorization.Privilege;
+
+/**
+ * RangerHiveAuthorizationPlugin is a plugin for Apache Ranger to manage the Hive authorization of
+ * the Apache Gravitino.
+ */
+public class RangerHiveAuthorizationPlugin extends RangerAuthorizationPlugin {
+ public RangerHiveAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super(catalogProvider, config);
+ }
+
+ /**
+ * Ranger hive's privilege have `select`, `update`, `create`, `drop`, `alter`, `index`, `lock`,
+ * `read`, `write`, `repladmin`, `serviceadmin`, `refresh` and `all`. Reference:
+ * ranger/agents-common/src/main/resources/service-defs/ranger-servicedef-hive.json
+ */
+ @Override
+ protected void initMapPrivileges() {
+ mapPrivileges =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
Review Comment:
These are two scenarios here:
1. If you have SecurableObjects('catalog.schema.*', CREATE_TABLE), this permission mean is you can create any table under the `catalog.schema`.
2. If you have SecurableObjects('catalog.schema.tab1', CREATE_TABLE), this permission mean is you can create table `tab1` under the `catalog.schema`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#issuecomment-2297911224
hi @jerqi
> Do you have e2e tests for this pull request?
Sure, IT in the `RangerHiveIT.java`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724766504
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHelper.java:
##########
@@ -0,0 +1,533 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This class is a helper class for the Ranger authorization plugin. It provides the ability to
+ * manage the Ranger policies and roles.
+ */
+public class RangerHelper {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerHelper.class);
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ RangerAuthorizationPlugin rangerAuthorizationPlugin;
+
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ /** The owner privileges, the owner can do anything on the metadata object */
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise search, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, If you use `db.table` condition to search policy, the Ranger will
+ * match `db1.table1`, `db1.table2`, `db*.table*`, So we need to manually precisely filter this
+ * research results. <br>
+ * policySearchKeys: The search Ranger policy condition key defines. <br>
+ * policyPreciseFilterKeys: The precise filter Ranger search results key defines <br>
+ */
+ protected List<String> policySearchKeys = null;
+
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public RangerHelper(RangerAuthorizationPlugin rangerAuthorizationPlugin, String catalogProvider) {
+ this.rangerAuthorizationPlugin = rangerAuthorizationPlugin;
+ switch (catalogProvider) {
+ case "hive":
+ initPrivilegesMapping();
+ initOwnerPrivileges();
+ initPolicySearchKeys();
+ initPreciseFilterKeys();
+ break;
+ default:
+ throw new IllegalArgumentException(
+ "Authorization plugin unsupported catalog provider: " + catalogProvider);
+ }
+ }
+
+ /** Initial mapping Gravitino privilege name to the underlying authorization system privileges. */
+ private void initPrivilegesMapping() {
+ privilegesMapping =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.MODIFY_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_UPDATE,
+ RangerDefines.ACCESS_TYPE_HIVE_ALTER,
+ RangerDefines.ACCESS_TYPE_HIVE_WRITE))
+ .put(
+ Privilege.Name.SELECT_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_READ, RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .build();
+ }
+
+ /** Initial Owner privileges */
+ private void initOwnerPrivileges() {
+ ownerPrivileges = ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_ALL);
+ }
+
+ /** Initial Ranger policy search key defines */
+ private void initPolicySearchKeys() {
+ policySearchKeys =
+ Arrays.asList(
+ RangerDefines.SEARCH_FILTER_DATABASE,
+ RangerDefines.SEARCH_FILTER_TABLE,
+ RangerDefines.SEARCH_FILTER_COLUMN);
+ }
+
+ /** Initial precise filter key defines */
+ private void initPreciseFilterKeys() {
+ policyPreciseFilterKeys =
+ Arrays.asList(
+ RangerDefines.RESOURCE_DATABASE,
+ RangerDefines.RESOURCE_TABLE,
+ RangerDefines.RESOURCE_COLUMN);
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Set<String> setAccesses = new HashSet<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (setAccesses.contains(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ setAccesses.add(access.getType());
+ });
+ }
+
+ /**
+ * Add policy item access items base the securable object's privileges. <br>
+ * We didn't clean the policy items because one Ranger policy maybe contains multiple Gravitino
+ * securable objects. <br>
+ */
+ void addPolicyItem(RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkPrivileges(securableObject);
+
+ // Add the policy items by the securable object's privileges
+ securableObject
+ .privileges()
+ .forEach(
+ gravitinoPrivilege -> {
+ // Translate the Gravitino privilege to map Ranger privilege
+ rangerAuthorizationPlugin
+ .translatePrivilege(gravitinoPrivilege.name())
+ .forEach(
+ mappedPrivilege -> {
Review Comment:
Could you extract a method for `matchingPrivilege`? Many places use this.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu merged PR #4515:
URL: https://github.com/apache/gravitino/pull/4515
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724849823
##########
authorizations/authorization-ranger/src/main/resources/META-INF/services/org.apache.gravitino.connector.authorization.AuthorizationProvider:
##########
@@ -0,0 +1,19 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+org.apache.gravitino.authorization.ranger.RangerAuthorization
Review Comment:
We can add multiple Authorization in the `authorization.AuthorizationProvider`, just like
https://github.com/apache/gravitino/blob/main/core/src/test/resources/META-INF/services/org.apache.gravitino.connector.authorization.AuthorizationProvider#L19
Look more carefully before you jump to conclusions
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#issuecomment-2295560694
> I found that there are differences between the construction the ranger policy and our implementation.
>
> If the policyName is `roleName + securableObjectFullName`, it's possible that there will be many policies for the same resource, which seems unnecessary.
>
> In our system, each policy corresponds to a single resource, and the policy is named based on the resource name. Within Ranger, we create roles in ranger, instead of putting the role in the policyName, we will put the role and role privileges into policyItems.
hi @lw-yang
So does Gravitino.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#issuecomment-2298063495
> > hi @jerqi
> > > Do you have e2e tests for this pull request?
> >
> >
> > Sure, IT in the `RangerHiveIT.java`
>
> Do you start a Gravitino Server in the test?
I have another PR waiting to submit, It's includes Gravitino Server RESTful E2E test, https://github.com/xunliu/gravitino/blob/issue-3963-4460/integration-test/src/test/java/org/apache/gravitino/integration/test/authorization/ranger/RangerHiveAuthorizationIT.java#L97
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724198950
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ mapAccesses.put(access.getType(), true);
+ });
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy exists but has different privileges, also return true. Because one Ranger
+ * policy maybe contain multiple Gravitino securable object <br>
+ * 4. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravition securable object's privilege
+ // and roleName
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If exist policy and have same privilege then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(change.getSecurableObject().fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(
+ SecurableObjects.DOT_SPLITTER.splitToList(change.getSecurableObject().fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+ }
+
+ addPolicyItem(policy, change.getRoleName(), change.getSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return true;
+ }
+
+ /**
+ * Remove the securable object's privilege from the policy. <br>
+ * Because Ranger use unique metadata to location Ranger policy and manage the all privileges, So
+ * one Ranger policy maybe contain multiple Gravitino privilege objects. <br>
+ * Remove Ranger policy item condition is: <br>
+ * 1. This Ranger policy item's accesses equal the Gravition securable object's privilege. <br>
+ * 2. This Ranger policy item's users and groups is empty. <br>
+ * If policy didn't have any policy item, then delete this policy: <br>
+ */
+ private boolean doRemoveSecurableObject(
+ String roleName, RoleChange.RemoveSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ policy
+ .getPolicyItems()
+ .forEach(
+ policyItem -> {
+ boolean match =
+ policyItem.getAccesses().stream()
+ .allMatch(
+ // Find the policy item that match access and role
+ access -> {
+ // Use Gravitino privilege to search the Ranger policy item's access
+ boolean matchPrivilege =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(
+ privilege ->
+ translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .anyMatch(privilege -> privilege.equals(access.getType()));
+ return matchPrivilege;
+ });
+ if (match) {
+ policyItem.getRoles().removeIf(roleName::equals);
+ }
+ });
+
+ // If the policy does have any role and user and group, then remove it.
+ policy
+ .getPolicyItems()
+ .removeIf(
+ policyItem ->
+ policyItem.getRoles().isEmpty()
+ && policyItem.getUsers().isEmpty()
+ && policyItem.getGroups().isEmpty());
+
+ try {
+ if (policy.getPolicyItems().size() == 0) {
+ rangerClient.deletePolicy(policy.getId());
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ LOG.error("Failed to remove the policy item from the Ranger policy {}!", policy);
+ throw new RuntimeException(e);
+ }
+ } else {
+ LOG.warn(
+ "Cannot find the Ranger policy({}) for the Gravitino securable object({})!",
+ roleName,
+ change.getSecurableObject().fullName());
+ // Don't throw exception or return false, because need support immutable operation.
+ }
+ return true;
+ }
+
+ /**
+ * 1. Find the policy base securable object. <br>
+ * 2. If the policy is exist, then user new securable object's privilege to update. <br>
+ * 3. If the policy is not exist return false. <br>
+ */
+ private boolean doUpdateSecurableObject(
+ String roleName, RoleChange.UpdateSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ removePolicyItem(policy, roleName, change.getSecurableObject());
+ addPolicyItem(policy, roleName, change.getNewSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ } else {
+ LOG.warn(
+ "Cannot find the policy({}) for the securable object({})!",
+ roleName,
+ change.getSecurableObject().fullName());
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Add policy item access items base the securable object's privileges. <br>
+ * We didn't clean the policy items, because one Ranger policy maybe contain multiple Gravitino
+ * securable objects. <br>
+ */
+ private void addPolicyItem(
+ RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkSecurableObject(securableObject);
+
+ // Add the policy items by the securable object's privileges
+ securableObject
+ .privileges()
+ .forEach(
+ gravitinoPrivilege -> {
+ // Translate the Gravitino privilege to map Ranger privilege
+ translatePrivilege(gravitinoPrivilege.name())
+ .forEach(
+ mappedPrivilege -> {
+ // Find the policy item that matches Gravitino privilege
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItems =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ access -> access.getType().equals(mappedPrivilege));
+ })
+ .collect(Collectors.toList());
+
+ if (matchPolicyItems.size() == 0) {
+ // If the policy item does not exist, then create a new policy item
+ RangerPolicy.RangerPolicyItem policyItem =
+ new RangerPolicy.RangerPolicyItem();
+ RangerPolicy.RangerPolicyItemAccess access =
+ new RangerPolicy.RangerPolicyItemAccess();
+ access.setType(mappedPrivilege);
+ policyItem.getAccesses().add(access);
+ policyItem.getRoles().add(roleName);
+ if (Privilege.Condition.ALLOW == gravitinoPrivilege.condition()) {
+ policy.getPolicyItems().add(policyItem);
+ } else {
+ policy.getDenyPolicyItems().add(policyItem);
+ }
+ } else {
+ // If the policy item exists, then add the role to the policy item
+ matchPolicyItems.stream()
+ .forEach(
+ policyItem -> {
+ // If the role is not in the policy item, then add it
+ if (!policyItem.getRoles().contains(roleName)) {
+ policyItem.getRoles().add(roleName);
+ }
+ });
+ }
+ });
+ });
+ }
+
+ /**
+ * Remove policy item base the securable object's privileges and role name. <br>
+ * We didn't directly clean the policy items, because one Ranger policy maybe contain multiple
+ * Gravitino privilege objects. <br>
+ */
+ private void removePolicyItem(
+ RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkSecurableObject(securableObject);
+
+ // Delete the policy role base the securable object's privileges
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ boolean matchPrivilege =
+ securableObject.privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .anyMatch(
+ privilege -> {
+ return access.getType().equals(privilege);
+ });
+ if (matchPrivilege
+ && !policyItem.getUsers().isEmpty()
+ && !policyItem.getGroups().isEmpty()) {
+ // Not ownership policy item, then remove the role
+ policyItem.getRoles().removeIf(roleName::equals);
+ }
+ });
+ });
+
+ // Delete the policy items if the roles is empty and not ownership policy item
+ policy
+ .getPolicyItems()
+ .removeIf(
+ policyItem -> {
+ return policyItem.getRoles().isEmpty()
+ && policyItem.getUsers().isEmpty()
+ && policyItem.getGroups().isEmpty();
+ });
+ }
+
+ private boolean checkSecurableObject(SecurableObject securableObject) {
+ securableObject
+ .privileges()
+ .forEach(
+ privilege -> {
+ check(
+ checkPrivilege(privilege.name()),
+ "This privilege %s is not support in the Ranger hive authorization",
Review Comment:
`UseSchema` `CreateCatalog` will be pushed to Ranger, too.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724753495
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,583 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.authorization.ranger.reference.VXGroup;
+import org.apache.gravitino.authorization.ranger.reference.VXGroupList;
+import org.apache.gravitino.authorization.ranger.reference.VXUser;
+import org.apache.gravitino.authorization.ranger.reference.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Ranger authorization operations plugin abstract class. <br>
+ * 1. For Ranger limit, The same metadata object only has a unique Ranger policy, So a Ranger policy
+ * maybe contains multiple Gravitino securable objects. <br>
+ * 2. For easy management, each Ranger privilege will create one RangerPolicyItemAccess in the
+ * policy. <br>
+ * 3. Ranger also have Role concept, and support adds multiple users or groups in the Ranger Role,
+ * So we can use the Ranger Role to implement the Gravitino Role. <br>
+ * 4. The Ranger policy also supports multiple users and groups, But we only use a user or group to
+ * implement Gravitino Owner concept. <br>
+ */
+public class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected String rangerServiceName;
+ protected RangerClientExtend rangerClient;
+ private RangerHelper rangerHelper;
+ @VisibleForTesting public final String rangerAdminName;
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ rangerAdminName = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ RangerHelper.check(rangerUrl != null, "Ranger admin URL is required");
+ RangerHelper.check(authType != null, "Ranger auth type is required");
+ RangerHelper.check(rangerAdminName != null, "Ranger username is required");
+ RangerHelper.check(password != null, "Ranger password is required");
+ RangerHelper.check(rangerServiceName != null, "Ranger service name is required");
+ rangerClient = new RangerClientExtend(rangerUrl, authType, rangerAdminName, password);
+ rangerHelper = new RangerHelper(this, catalogProvider);
+ }
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return rangerHelper.privilegesMapping.get(name);
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(rangerHelper.ownerPrivileges);
+ }
+
+ /**
+ * Create a new role in the Ranger. <br>
+ * 1. Create a policy for metadata object. <br>
+ * 2. Save role name in the Policy items. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ return rangerHelper.checkRangerRole(role.name());
+ }
+
+ /** Remove the role name from the Ranger policy item, and delete this Role in the Ranger. <br> */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, delete the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), rangerAdminName, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult = doRemoveSecurableObject((RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult = doUpdateSecurableObject((RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ * 1. If the metadata object already has an owner, then transfer the ownership from preOwner to
+ * newOwner, The function params preOwner and newOwner don't equal null. <br>
+ * 2. If the metadata object doesn't have an owner, then set the owner to newOwner, The function
+ * params preOwner equal null and newOwner don't equal null. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object.
+ * @param newOwner The new owner of the metadata object.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ RangerHelper.check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = rangerHelper.findManagedPolicy(metadataObject);
+ try {
+ if (policy == null) {
+ policy = rangerHelper.addOwnerToNewPolicy(metadataObject, newOwner);
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerHelper.updatePolicyOwner(policy, preOwner, newOwner);
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this user to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param user The user to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role: {} to user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this user from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param user The user to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this group to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Grant role: {} to group: {} failed!", role, group, e);
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this group from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param group The group to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from group: {} failed!", role, group, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
Review Comment:
```suggestion
LOG.warn("The user({}) doesn't exist in the Ranger!", user);
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724753165
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,583 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.authorization.ranger.reference.VXGroup;
+import org.apache.gravitino.authorization.ranger.reference.VXGroupList;
+import org.apache.gravitino.authorization.ranger.reference.VXUser;
+import org.apache.gravitino.authorization.ranger.reference.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Ranger authorization operations plugin abstract class. <br>
+ * 1. For Ranger limit, The same metadata object only has a unique Ranger policy, So a Ranger policy
+ * maybe contains multiple Gravitino securable objects. <br>
+ * 2. For easy management, each Ranger privilege will create one RangerPolicyItemAccess in the
+ * policy. <br>
+ * 3. Ranger also have Role concept, and support adds multiple users or groups in the Ranger Role,
+ * So we can use the Ranger Role to implement the Gravitino Role. <br>
+ * 4. The Ranger policy also supports multiple users and groups, But we only use a user or group to
+ * implement Gravitino Owner concept. <br>
+ */
+public class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected String rangerServiceName;
+ protected RangerClientExtend rangerClient;
+ private RangerHelper rangerHelper;
+ @VisibleForTesting public final String rangerAdminName;
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ rangerAdminName = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ RangerHelper.check(rangerUrl != null, "Ranger admin URL is required");
+ RangerHelper.check(authType != null, "Ranger auth type is required");
+ RangerHelper.check(rangerAdminName != null, "Ranger username is required");
+ RangerHelper.check(password != null, "Ranger password is required");
+ RangerHelper.check(rangerServiceName != null, "Ranger service name is required");
+ rangerClient = new RangerClientExtend(rangerUrl, authType, rangerAdminName, password);
+ rangerHelper = new RangerHelper(this, catalogProvider);
+ }
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return rangerHelper.privilegesMapping.get(name);
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(rangerHelper.ownerPrivileges);
+ }
+
+ /**
+ * Create a new role in the Ranger. <br>
+ * 1. Create a policy for metadata object. <br>
+ * 2. Save role name in the Policy items. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ return rangerHelper.checkRangerRole(role.name());
+ }
+
+ /** Remove the role name from the Ranger policy item, and delete this Role in the Ranger. <br> */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, delete the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), rangerAdminName, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult = doRemoveSecurableObject((RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult = doUpdateSecurableObject((RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ * 1. If the metadata object already has an owner, then transfer the ownership from preOwner to
+ * newOwner, The function params preOwner and newOwner don't equal null. <br>
+ * 2. If the metadata object doesn't have an owner, then set the owner to newOwner, The function
+ * params preOwner equal null and newOwner don't equal null. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object.
+ * @param newOwner The new owner of the metadata object.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ RangerHelper.check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = rangerHelper.findManagedPolicy(metadataObject);
+ try {
+ if (policy == null) {
+ policy = rangerHelper.addOwnerToNewPolicy(metadataObject, newOwner);
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerHelper.updatePolicyOwner(policy, preOwner, newOwner);
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this user to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param user The user to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role: {} to user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this user from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param user The user to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this group to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Grant role: {} to group: {} failed!", role, group, e);
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this group from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param group The group to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from group: {} failed!", role, group, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
Review Comment:
```suggestion
LOG.warn("The user({}) doesn't exist in the Ranger!", user);
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1725005020
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,583 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.authorization.ranger.reference.VXGroup;
+import org.apache.gravitino.authorization.ranger.reference.VXGroupList;
+import org.apache.gravitino.authorization.ranger.reference.VXUser;
+import org.apache.gravitino.authorization.ranger.reference.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Ranger authorization operations plugin abstract class. <br>
+ * 1. For Ranger limit, The same metadata object only has a unique Ranger policy, So a Ranger policy
+ * maybe contains multiple Gravitino securable objects. <br>
+ * 2. For easy management, each Ranger privilege will create one RangerPolicyItemAccess in the
+ * policy. <br>
+ * 3. Ranger also have Role concept, and support adds multiple users or groups in the Ranger Role,
+ * So we can use the Ranger Role to implement the Gravitino Role. <br>
+ * 4. The Ranger policy also supports multiple users and groups, But we only use a user or group to
+ * implement Gravitino Owner concept. <br>
+ */
+public class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected String rangerServiceName;
+ protected RangerClientExtend rangerClient;
+ private RangerHelper rangerHelper;
+ @VisibleForTesting public final String rangerAdminName;
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ rangerAdminName = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ RangerHelper.check(rangerUrl != null, "Ranger admin URL is required");
+ RangerHelper.check(authType != null, "Ranger auth type is required");
+ RangerHelper.check(rangerAdminName != null, "Ranger username is required");
+ RangerHelper.check(password != null, "Ranger password is required");
+ RangerHelper.check(rangerServiceName != null, "Ranger service name is required");
+ rangerClient = new RangerClientExtend(rangerUrl, authType, rangerAdminName, password);
+ rangerHelper = new RangerHelper(this, catalogProvider);
+ }
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return rangerHelper.privilegesMapping.get(name);
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(rangerHelper.ownerPrivileges);
+ }
+
+ /**
+ * Create a new role in the Ranger. <br>
+ * 1. Create a policy for metadata object. <br>
+ * 2. Save role name in the Policy items. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ return rangerHelper.checkRangerRole(role.name());
+ }
+
+ /** Remove the role name from the Ranger policy item, and delete this Role in the Ranger. <br> */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, delete the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), rangerAdminName, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult = doRemoveSecurableObject((RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult = doUpdateSecurableObject((RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ * 1. If the metadata object already has an owner, then transfer the ownership from preOwner to
+ * newOwner, The function params preOwner and newOwner don't equal null. <br>
+ * 2. If the metadata object doesn't have an owner, then set the owner to newOwner, The function
+ * params preOwner equal null and newOwner don't equal null. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object.
+ * @param newOwner The new owner of the metadata object.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ RangerHelper.check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = rangerHelper.findManagedPolicy(metadataObject);
+ try {
+ if (policy == null) {
+ policy = rangerHelper.addOwnerToNewPolicy(metadataObject, newOwner);
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerHelper.updatePolicyOwner(policy, preOwner, newOwner);
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this user to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param user The user to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role: {} to user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this user from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param user The user to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
Review Comment:
If we return the value, we should check the return value. It's more safer. Otherwise, it will be weird for other maintainers.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1721400865
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
Review Comment:
OK, Add LOG printing.
##########
authorizations/authorization-ranger/build.gradle.kts:
##########
@@ -0,0 +1,113 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+description = "authorization-ranger"
+
+plugins {
+ `maven-publish`
+ id("java")
+ id("idea")
+}
+
+dependencies {
+ implementation(project(":api")) {
+ exclude(group = "*")
+ }
+ implementation(project(":core"))
Review Comment:
DONE
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy is not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilege -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilege))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role is not exist. */
+ private RangerRole createRangerRole(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role is not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy manage, each privilege will create a RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege in the delegate Gravitino management policy ");
+ }
+ mapAccesses.put(access.getType(), true);
+ });
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
Review Comment:
DONE
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy is not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilege -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilege))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role is not exist. */
+ private RangerRole createRangerRole(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role is not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy manage, each privilege will create a RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege in the delegate Gravitino management policy ");
Review Comment:
DONE
##########
api/src/main/java/org/apache/gravitino/authorization/RoleChange.java:
##########
@@ -149,7 +189,101 @@ public int hashCode() {
*/
@Override
public String toString() {
- return "REMOVESECURABLEOBJECT " + securableObject;
+ return "REMOVESECURABLEOBJECT " + roleName + " " + securableObject;
+ }
+ }
+
+ /**
+ * A UpdateSecurableObject is to update securable object's privilege from role. <br>
+ * The securable object's metadata entity must be the same as new securable object's metadata
+ * entity. <br>
+ * The securable object's privilege must be different as new securable object's privilege. <br>
+ */
+ final class UpdateSecurableObject implements RoleChange {
+ private final String roleName;
+ private final SecurableObject securableObject;
+ private final SecurableObject newSecurableObject;
+
+ private UpdateSecurableObject(
+ String roleName, SecurableObject securableObject, SecurableObject newSecurableObject) {
+ if (!securableObject.fullName().equals(newSecurableObject.fullName())) {
+ throw new IllegalArgumentException(
+ "The securable object's metadata entity must be same as new securable object's metadata entity.");
+ }
+ if (securableObject.privileges().containsAll(newSecurableObject.privileges())) {
+ throw new IllegalArgumentException(
+ "The updated securable object's privilege must be different as new securable object's privilege.");
Review Comment:
DONE.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHiveAuthorizationPlugin.java:
##########
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Set;
+import org.apache.gravitino.authorization.Privilege;
+
+/**
+ * RangerHiveAuthorizationPlugin is a plugin for Apache Ranger to manage the Hive authorization of
+ * the Apache Gravitino.
+ */
+public class RangerHiveAuthorizationPlugin extends RangerAuthorizationPlugin {
+ public RangerHiveAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super(catalogProvider, config);
+ }
+
+ /**
+ * Ranger hive's privilege have `select`, `update`, `create`, `drop`, `alter`, `index`, `lock`,
+ * `read`, `write`, `repladmin`, `serviceadmin`, `refresh` and `all`. Reference:
+ * ranger/agents-common/src/main/resources/service-defs/ranger-servicedef-hive.json
+ */
+ @Override
+ protected void initMapPrivileges() {
+ mapPrivileges =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
Review Comment:
Apache Ranger doesn't have `use catalog` and `use schema` privilege.
##########
api/src/main/java/org/apache/gravitino/authorization/RoleChange.java:
##########
@@ -149,7 +189,101 @@ public int hashCode() {
*/
@Override
public String toString() {
- return "REMOVESECURABLEOBJECT " + securableObject;
+ return "REMOVESECURABLEOBJECT " + roleName + " " + securableObject;
+ }
+ }
+
+ /**
+ * A UpdateSecurableObject is to update securable object's privilege from role. <br>
+ * The securable object's metadata entity must be the same as new securable object's metadata
+ * entity. <br>
+ * The securable object's privilege must be different as new securable object's privilege. <br>
+ */
+ final class UpdateSecurableObject implements RoleChange {
+ private final String roleName;
+ private final SecurableObject securableObject;
+ private final SecurableObject newSecurableObject;
+
+ private UpdateSecurableObject(
+ String roleName, SecurableObject securableObject, SecurableObject newSecurableObject) {
+ if (!securableObject.fullName().equals(newSecurableObject.fullName())) {
+ throw new IllegalArgumentException(
+ "The securable object's metadata entity must be same as new securable object's metadata entity.");
+ }
+ if (securableObject.privileges().containsAll(newSecurableObject.privileges())) {
Review Comment:
Because the securable object's privilege must be different as new securable object's privilege.
I changed this code.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
Review Comment:
If grant operation failed then return false.
##########
core/src/main/java/org/apache/gravitino/connector/authorization/UserGroupAuthorizationPlugin.java:
##########
@@ -98,46 +98,15 @@ interface UserGroupAuthorizationPlugin {
Boolean onGroupAcquired(Group group) throws RuntimeException;
/**
- * After granting roles to a user from Gravitino, this method is called to grant roles to the user
- * in the underlying system. <br>
- *
- * @param user The entity of the User.
- * @param roles The entities of the Roles.
- * @return True if the Grant was successful, false if the Grant was failed.
- * @throws RuntimeException If granting roles to a user encounters storage issues.
- */
- Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException;
-
- /**
- * After revoking roles from a user from Gravitino, this method is called to revoke roles from the
- * user in the underlying system. <br>
- *
- * @param user The entity of the User.
- * @param roles The entities of the Roles.
- * @return True if the revoke was successfully removed, false if the revoke failed.
- * @throws RuntimeException If revoking roles from a user encounters storage issues.
- */
- Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException;
-
- /**
- * After granting roles to a group from Gravitino, this method is called to grant roles to the
- * group in the underlying system. <br>
- *
- * @param group The entity of the Group.
- * @param roles The entities of the Roles.
- * @return True if the revoke was successfully removed, False if the revoke failed.
- * @throws RuntimeException If granting roles to a group encounters storage issues.
- */
- Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException;
-
- /**
- * After revoking roles from a group from Gravitino, this method is called to revoke roles from
- * the group in the underlying system. <br>
+ * After set a Owner to Gravitino, this method is called to set the Owner to the underlying
+ * system. <br>
*
- * @param group The entity of the Group.
- * @param roles The entities of the Roles.
- * @return True if the revoke was successfully removed, False if the revoke failed.
- * @throws RuntimeException If revoking roles from a group encounters storage issues.
+ * @param metadataObject The metadata entity.
+ * @param preOwner The previous owner.
+ * @param newOwner The new owner.
+ * @return True if the set Owner was successfully set, false if the set Owner failed.
+ * @throws RuntimeException If adding the Group encounters storage issues.
*/
- Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException;
+ Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
Review Comment:
This PR implements all authorization functions.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy is not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilege -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilege))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+
+ return Boolean.TRUE;
Review Comment:
DONE
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy is not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilege -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilege))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role is not exist. */
+ private RangerRole createRangerRole(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role is not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy manage, each privilege will create a RangerPolicyItemAccess in the policy.
Review Comment:
DONE
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy is not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilege -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilege))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role is not exist. */
+ private RangerRole createRangerRole(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role is not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy manage, each privilege will create a RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
Review Comment:
Each privilege will create one RangerPolicyItemAccess in the policy, So it must equal one.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerClientExt.java:
##########
@@ -0,0 +1,184 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.collect.ImmutableMap;
+import com.sun.jersey.api.client.GenericType;
+import com.sun.jersey.api.client.UniformInterfaceException;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Map;
+import javax.ws.rs.HttpMethod;
+import javax.ws.rs.core.Response;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.ranger.RangerClient;
+import org.apache.ranger.RangerServiceException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Apache Ranger client extension <br>
+ * The class extends the RangerClient class and provides additional methods to create, search and
+ * delete users and groups
+ */
+public class RangerClientExt extends RangerClient {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerClientExt.class);
+ private static final String URI_USER_BASE = "/service/xusers/users";
+ private static final String URI_USER_BY_ID = URI_USER_BASE + "/%d";
+ private static final String URI_GROUP_BASE = "/service/xusers/groups";
+ private static final String URI_GROUP_BY_ID = URI_GROUP_BASE + "/%d";
+ private static final String URI_CREATE_EXTERNAL_USER = URI_USER_BASE + "/external";
+
+ // Ranger user APIs
+ private static final API SEARCH_USER = new API(URI_USER_BASE, HttpMethod.GET, Response.Status.OK);
+ private static final API CREATE_EXTERNAL_USER =
+ new API(URI_CREATE_EXTERNAL_USER, HttpMethod.POST, Response.Status.OK);
+ private static final API DELETE_USER =
+ new API(URI_USER_BY_ID, HttpMethod.DELETE, Response.Status.NO_CONTENT);
+
+ // Ranger group APIs
+ private static final API CREATE_GROUP =
+ new API(URI_GROUP_BASE, HttpMethod.POST, Response.Status.OK);
+ private static final API SEARCH_GROUP =
+ new API(URI_GROUP_BASE, HttpMethod.GET, Response.Status.OK);
+ // private static final API GET_GROUP = new API(URI_GROUP_BY_ID, HttpMethod.GET,
+ // Response.Status.OK);
+ private static final API DELETE_GROUP =
+ new API(URI_GROUP_BY_ID, HttpMethod.DELETE, Response.Status.NO_CONTENT);
+
+ // apache/ranger/intg/src/main/java/org/apache/ranger/RangerClient.java
+ // The private method callAPI of Ranger is called by reflection
+ // private <T> T callAPI(API api, Map<String, String> params, Object request, GenericType<T>
+ // responseType) throws RangerServiceException
+ private Method callAPIMethodGenericResponseType;
+
+ // private <T> T callAPI(API api, Map<String, String> params, Object request, Class<T>
+ // responseType) throws RangerServiceException
+ private Method callAPIMethodClassResponseType;
+ // private void callAPI(API api, Map<String, String> params) throws RangerServiceException
+ private Method callAPIMethodNonResponse;
+
+ public RangerClientExt(String hostName, String authType, String username, String password) {
+ super(hostName, authType, username, password, null);
+
+ // initialize callAPI method
+ try {
+ callAPIMethodGenericResponseType =
+ RangerClient.class.getDeclaredMethod(
+ "callAPI", API.class, Map.class, Object.class, GenericType.class);
+ callAPIMethodGenericResponseType.setAccessible(true);
+
+ callAPIMethodNonResponse =
+ RangerClient.class.getDeclaredMethod("callAPI", API.class, Map.class);
+ callAPIMethodNonResponse.setAccessible(true);
+
+ callAPIMethodClassResponseType =
+ RangerClient.class.getDeclaredMethod(
+ "callAPI", API.class, Map.class, Object.class, Class.class);
+ callAPIMethodClassResponseType.setAccessible(true);
+ } catch (NoSuchMethodException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public Boolean createUser(VXUser user) throws RuntimeException {
+ try {
+ callAPIMethodClassResponseType.invoke(this, CREATE_EXTERNAL_USER, null, user, VXUser.class);
+ } catch (UniformInterfaceException e) {
+ LOG.error("Failed to create user: " + e.getResponse().getEntity(String.class));
+ return Boolean.FALSE;
+ } catch (InvocationTargetException | IllegalAccessException e) {
+ Throwable cause = e.getCause();
+ if (cause instanceof com.sun.jersey.api.client.UniformInterfaceException) {
+ com.sun.jersey.api.client.UniformInterfaceException uniformException =
+ (com.sun.jersey.api.client.UniformInterfaceException) cause;
+ int statusCode = uniformException.getResponse().getStatus();
+ if (statusCode == 204) {
+ // Because Ranger use asynchronous create user, so the response status is 204, research
+ // the user to check if it is created
+ VXUserList userList = searchUser(ImmutableMap.of("name", user.getName()));
Review Comment:
Yes.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1023 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
Review Comment:
DONE
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy is not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilege -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilege))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role is not exist. */
+ private RangerRole createRangerRole(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role is not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy manage, each privilege will create a RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege in the delegate Gravitino management policy ");
+ }
+ mapAccesses.put(access.getType(), true);
+ });
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy is exist and have same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy is exist but have different privilege, also return true. Because one Ranger
+ * policy maybe contain multiple Gravitino securable object <br>
+ * 4. If the policy is not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravition securable object's privilege
+ // and roleName
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If exist policy and have same privilege then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
Review Comment:
This `else` can't be remove
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1023 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy is not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilege -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilege))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
Review Comment:
DONE
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724283105
##########
integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/RangerContainer.java:
##########
@@ -40,15 +40,18 @@ public class RangerContainer extends BaseContainer {
public static final int RANGER_SERVER_PORT = 6080;
public RangerClient rangerClient;
private String rangerUrl;
- private static final String username = "admin";
- // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
- private static final String password = "rangerR0cks!";
/**
- * for kerberos authentication: authType = "kerberos" username = principal password = path of the
- * keytab file
+ * for kerberos authentication: <br>
+ * authType = "kerberos" <br>
+ * username = principal <br>
+ * password = path of the keytab file <br>
*/
- private static final String authType = "simple";
+ public static final String authType = "simple";
+
+ public static final String rangerUserName = "admin";
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
Review Comment:
This is Apache Ranger origion comments, https://github.com/apache/ranger/blob/master/security-admin/scripts/install.properties#L84
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1721492852
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerClientExt.java:
##########
@@ -0,0 +1,184 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.collect.ImmutableMap;
+import com.sun.jersey.api.client.GenericType;
+import com.sun.jersey.api.client.UniformInterfaceException;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Map;
+import javax.ws.rs.HttpMethod;
+import javax.ws.rs.core.Response;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.ranger.RangerClient;
+import org.apache.ranger.RangerServiceException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Apache Ranger client extension <br>
+ * The class extends the RangerClient class and provides additional methods to create, search and
+ * delete users and groups
+ */
+public class RangerClientExt extends RangerClient {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerClientExt.class);
+ private static final String URI_USER_BASE = "/service/xusers/users";
+ private static final String URI_USER_BY_ID = URI_USER_BASE + "/%d";
+ private static final String URI_GROUP_BASE = "/service/xusers/groups";
+ private static final String URI_GROUP_BY_ID = URI_GROUP_BASE + "/%d";
+ private static final String URI_CREATE_EXTERNAL_USER = URI_USER_BASE + "/external";
+
+ // Ranger user APIs
+ private static final API SEARCH_USER = new API(URI_USER_BASE, HttpMethod.GET, Response.Status.OK);
+ private static final API CREATE_EXTERNAL_USER =
+ new API(URI_CREATE_EXTERNAL_USER, HttpMethod.POST, Response.Status.OK);
+ private static final API DELETE_USER =
+ new API(URI_USER_BY_ID, HttpMethod.DELETE, Response.Status.NO_CONTENT);
+
+ // Ranger group APIs
+ private static final API CREATE_GROUP =
+ new API(URI_GROUP_BASE, HttpMethod.POST, Response.Status.OK);
+ private static final API SEARCH_GROUP =
+ new API(URI_GROUP_BASE, HttpMethod.GET, Response.Status.OK);
+ // private static final API GET_GROUP = new API(URI_GROUP_BY_ID, HttpMethod.GET,
+ // Response.Status.OK);
+ private static final API DELETE_GROUP =
+ new API(URI_GROUP_BY_ID, HttpMethod.DELETE, Response.Status.NO_CONTENT);
+
+ // apache/ranger/intg/src/main/java/org/apache/ranger/RangerClient.java
+ // The private method callAPI of Ranger is called by reflection
+ // private <T> T callAPI(API api, Map<String, String> params, Object request, GenericType<T>
+ // responseType) throws RangerServiceException
+ private Method callAPIMethodGenericResponseType;
+
+ // private <T> T callAPI(API api, Map<String, String> params, Object request, Class<T>
+ // responseType) throws RangerServiceException
+ private Method callAPIMethodClassResponseType;
+ // private void callAPI(API api, Map<String, String> params) throws RangerServiceException
+ private Method callAPIMethodNonResponse;
+
+ public RangerClientExt(String hostName, String authType, String username, String password) {
+ super(hostName, authType, username, password, null);
+
+ // initialize callAPI method
+ try {
+ callAPIMethodGenericResponseType =
+ RangerClient.class.getDeclaredMethod(
+ "callAPI", API.class, Map.class, Object.class, GenericType.class);
+ callAPIMethodGenericResponseType.setAccessible(true);
+
+ callAPIMethodNonResponse =
+ RangerClient.class.getDeclaredMethod("callAPI", API.class, Map.class);
+ callAPIMethodNonResponse.setAccessible(true);
+
+ callAPIMethodClassResponseType =
+ RangerClient.class.getDeclaredMethod(
+ "callAPI", API.class, Map.class, Object.class, Class.class);
+ callAPIMethodClassResponseType.setAccessible(true);
+ } catch (NoSuchMethodException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public Boolean createUser(VXUser user) throws RuntimeException {
+ try {
+ callAPIMethodClassResponseType.invoke(this, CREATE_EXTERNAL_USER, null, user, VXUser.class);
+ } catch (UniformInterfaceException e) {
+ LOG.error("Failed to create user: " + e.getResponse().getEntity(String.class));
+ return Boolean.FALSE;
+ } catch (InvocationTargetException | IllegalAccessException e) {
+ Throwable cause = e.getCause();
+ if (cause instanceof com.sun.jersey.api.client.UniformInterfaceException) {
+ com.sun.jersey.api.client.UniformInterfaceException uniformException =
+ (com.sun.jersey.api.client.UniformInterfaceException) cause;
+ int statusCode = uniformException.getResponse().getStatus();
+ if (statusCode == 204) {
+ // Because Ranger use asynchronous create user, so the response status is 204, research
+ // the user to check if it is created
+ VXUserList userList = searchUser(ImmutableMap.of("name", user.getName()));
Review Comment:
Can we be assured that the user has already been created by calling "searchUser"?
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerClientExt.java:
##########
@@ -0,0 +1,184 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.collect.ImmutableMap;
+import com.sun.jersey.api.client.GenericType;
+import com.sun.jersey.api.client.UniformInterfaceException;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.Map;
+import javax.ws.rs.HttpMethod;
+import javax.ws.rs.core.Response;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.ranger.RangerClient;
+import org.apache.ranger.RangerServiceException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Apache Ranger client extension <br>
+ * The class extends the RangerClient class and provides additional methods to create, search and
+ * delete users and groups
+ */
+public class RangerClientExt extends RangerClient {
Review Comment:
It's better to use full words.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1723297695
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ mapAccesses.put(access.getType(), true);
+ });
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy exists but has different privileges, also return true. Because one Ranger
+ * policy maybe contain multiple Gravitino securable object <br>
+ * 4. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravition securable object's privilege
+ // and roleName
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If exist policy and have same privilege then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(change.getSecurableObject().fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(
+ SecurableObjects.DOT_SPLITTER.splitToList(change.getSecurableObject().fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+ }
+
+ addPolicyItem(policy, change.getRoleName(), change.getSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return true;
+ }
+
+ /**
+ * Remove the securable object's privilege from the policy. <br>
+ * Because Ranger use unique metadata to location Ranger policy and manage the all privileges, So
+ * one Ranger policy maybe contain multiple Gravitino privilege objects. <br>
+ * Remove Ranger policy item condition is: <br>
+ * 1. This Ranger policy item's accesses equal the Gravition securable object's privilege. <br>
+ * 2. This Ranger policy item's users and groups is empty. <br>
+ * If policy didn't have any policy item, then delete this policy: <br>
+ */
+ private boolean doRemoveSecurableObject(
+ String roleName, RoleChange.RemoveSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ policy
+ .getPolicyItems()
+ .forEach(
+ policyItem -> {
+ boolean match =
+ policyItem.getAccesses().stream()
+ .allMatch(
+ // Find the policy item that match access and role
+ access -> {
+ // Use Gravitino privilege to search the Ranger policy item's access
+ boolean matchPrivilege =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(
+ privilege ->
+ translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .anyMatch(privilege -> privilege.equals(access.getType()));
+ return matchPrivilege;
+ });
+ if (match) {
+ policyItem.getRoles().removeIf(roleName::equals);
+ }
+ });
+
+ // If the policy does have any role and user and group, then remove it.
+ policy
+ .getPolicyItems()
+ .removeIf(
+ policyItem ->
+ policyItem.getRoles().isEmpty()
+ && policyItem.getUsers().isEmpty()
+ && policyItem.getGroups().isEmpty());
+
+ try {
+ if (policy.getPolicyItems().size() == 0) {
+ rangerClient.deletePolicy(policy.getId());
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ LOG.error("Failed to remove the policy item from the Ranger policy {}!", policy);
+ throw new RuntimeException(e);
+ }
+ } else {
+ LOG.warn(
+ "Cannot find the Ranger policy({}) for the Gravitino securable object({})!",
+ roleName,
+ change.getSecurableObject().fullName());
+ // Don't throw exception or return false, because need support immutable operation.
+ }
+ return true;
+ }
+
+ /**
+ * 1. Find the policy base securable object. <br>
+ * 2. If the policy is exist, then user new securable object's privilege to update. <br>
+ * 3. If the policy is not exist return false. <br>
+ */
+ private boolean doUpdateSecurableObject(
+ String roleName, RoleChange.UpdateSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ removePolicyItem(policy, roleName, change.getSecurableObject());
+ addPolicyItem(policy, roleName, change.getNewSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ } else {
+ LOG.warn(
+ "Cannot find the policy({}) for the securable object({})!",
+ roleName,
+ change.getSecurableObject().fullName());
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Add policy item access items base the securable object's privileges. <br>
+ * We didn't clean the policy items, because one Ranger policy maybe contain multiple Gravitino
+ * securable objects. <br>
+ */
+ private void addPolicyItem(
+ RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkSecurableObject(securableObject);
+
+ // Add the policy items by the securable object's privileges
+ securableObject
+ .privileges()
+ .forEach(
+ gravitinoPrivilege -> {
+ // Translate the Gravitino privilege to map Ranger privilege
+ translatePrivilege(gravitinoPrivilege.name())
+ .forEach(
+ mappedPrivilege -> {
+ // Find the policy item that matches Gravitino privilege
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItems =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ access -> access.getType().equals(mappedPrivilege));
+ })
+ .collect(Collectors.toList());
+
Review Comment:
Should you check `getDenyPolicyItem`, too?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1723281849
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
Review Comment:
```suggestion
* 2. Create a role in the Ranger if the role doesn't exist. <br>
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724468740
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
Review Comment:
Will it fail because of network timeout?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#issuecomment-2301655274
Thanks for your hard work! The code seems good shape.
There are some points to discuss with you.
1. Could you configure the catalog with other authorization plugin instead of RangerPlugin?
2. Some privileges like `use schema`, `use catalog`, `create catalog` could be pushed down underlying system, too. The check logic will throw exception for them.
3. We should reduce the duplicated code further as possible as we can.
4. If we use a label for Gravitino, but we don't have any catalog information. If we have two hive catalogs, catalog1 and catalog2, they have the same name schema schema1, will the policies influence each other?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724902782
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,583 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.authorization.ranger.reference.VXGroup;
+import org.apache.gravitino.authorization.ranger.reference.VXGroupList;
+import org.apache.gravitino.authorization.ranger.reference.VXUser;
+import org.apache.gravitino.authorization.ranger.reference.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Ranger authorization operations plugin abstract class. <br>
+ * 1. For Ranger limit, The same metadata object only has a unique Ranger policy, So a Ranger policy
+ * maybe contains multiple Gravitino securable objects. <br>
+ * 2. For easy management, each Ranger privilege will create one RangerPolicyItemAccess in the
+ * policy. <br>
+ * 3. Ranger also have Role concept, and support adds multiple users or groups in the Ranger Role,
+ * So we can use the Ranger Role to implement the Gravitino Role. <br>
+ * 4. The Ranger policy also supports multiple users and groups, But we only use a user or group to
+ * implement Gravitino Owner concept. <br>
+ */
+public class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected String rangerServiceName;
+ protected RangerClientExtend rangerClient;
+ private RangerHelper rangerHelper;
+ @VisibleForTesting public final String rangerAdminName;
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ rangerAdminName = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ RangerHelper.check(rangerUrl != null, "Ranger admin URL is required");
+ RangerHelper.check(authType != null, "Ranger auth type is required");
+ RangerHelper.check(rangerAdminName != null, "Ranger username is required");
+ RangerHelper.check(password != null, "Ranger password is required");
+ RangerHelper.check(rangerServiceName != null, "Ranger service name is required");
+ rangerClient = new RangerClientExtend(rangerUrl, authType, rangerAdminName, password);
+ rangerHelper = new RangerHelper(this, catalogProvider);
+ }
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return rangerHelper.privilegesMapping.get(name);
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(rangerHelper.ownerPrivileges);
+ }
+
+ /**
+ * Create a new role in the Ranger. <br>
+ * 1. Create a policy for metadata object. <br>
+ * 2. Save role name in the Policy items. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ return rangerHelper.checkRangerRole(role.name());
+ }
+
+ /** Remove the role name from the Ranger policy item, and delete this Role in the Ranger. <br> */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, delete the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), rangerAdminName, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult = doRemoveSecurableObject((RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult = doUpdateSecurableObject((RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ * 1. If the metadata object already has an owner, then transfer the ownership from preOwner to
+ * newOwner, The function params preOwner and newOwner don't equal null. <br>
+ * 2. If the metadata object doesn't have an owner, then set the owner to newOwner, The function
+ * params preOwner equal null and newOwner don't equal null. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object.
+ * @param newOwner The new owner of the metadata object.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ RangerHelper.check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = rangerHelper.findManagedPolicy(metadataObject);
+ try {
+ if (policy == null) {
+ policy = rangerHelper.addOwnerToNewPolicy(metadataObject, newOwner);
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerHelper.updatePolicyOwner(policy, preOwner, newOwner);
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this user to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param user The user to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role: {} to user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this user from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param user The user to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this group to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Grant role: {} to group: {} failed!", role, group, e);
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this group from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param group The group to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from group: {} failed!", role, group, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) already exists in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) doesn't exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) doesn't exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) doesn't exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) doesn't exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Add the securable object's privilege to the Ranger policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = rangerHelper.findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravitino securable object's privilege
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If it exists policy with the same privilege, then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(change.getSecurableObject().fullName());
+ policy.setPolicyLabels(Lists.newArrayList(RangerHelper.MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
Review Comment:
Could we extract a method from Line 452 - 469 to reduce duplicate code?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1717003314
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHiveAuthorizationPlugin.java:
##########
@@ -0,0 +1,840 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Privileges;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * RangerHiveAuthorizationPlugin is a plugin for Apache Ranger to manage the Hive authorization of
+ * the Apache Gravitino.
+ */
+public class RangerHiveAuthorizationPlugin extends RangerAuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerHiveAuthorizationPlugin.class);
+
+ public RangerHiveAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+ }
+
+ /**
+ * Ranger hive's privilege have `select`, `update`, `create`, `drop`, `alter`, `index`, `lock`,
+ * `read`, `write`, `repladmin`, `serviceadmin`, `refresh` and `all`.
+ *
+ * <p>Reference: ranger/agents-common/src/main/resources/service-defs/ranger-servicedef-hive.json
+ */
+ @Override
+ protected void initMapPrivileges() {
+ mapPrivileges =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(Privilege.Name.CREATE_SCHEMA, ImmutableSet.of("create"))
+ .put(Privilege.Name.CREATE_TABLE, ImmutableSet.of("create"))
+ .put(Privilege.Name.MODIFY_TABLE, ImmutableSet.of("update", "drop", "alter", "write"))
+ .put(Privilege.Name.SELECT_TABLE, ImmutableSet.of("read", "select"))
+ .build();
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ * Reference: https://github.com/apache/gravitino/issues/4509
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject(role.name(), (RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @VisibleForTesting
+ public List<Privilege> getAllPrivileges() {
+ return mapPrivileges.keySet().stream().map(Privileges::allow).collect(Collectors.toList());
+ }
+
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ List<Privilege> allPrivileges = getAllPrivileges();
+
+ SecurableObject securableObjects =
+ SecurableObjects.parse(metadataObject.fullName(), metadataObject.type(), allPrivileges);
+
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentUserName())
+ .withCreateTime(Instant.now())
+ .build();
+
+ RoleEntity role =
+ RoleEntity.builder()
+ .withId(0L)
+ .withName(OWNER_ROLE_NAME)
+ .withAuditInfo(auditInfo)
+ .withSecurableObjects(Lists.newArrayList(securableObjects))
+ .build();
+
+ Boolean execResult = onRoleCreated(role);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(0L)
+ .withName(preOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ execResult = onRevokedRolesFromUser(Lists.newArrayList(role), userEntity);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(0L)
+ .withName(preOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ execResult = onRevokedRolesFromGroup(Lists.newArrayList(role), groupEntity);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(0L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ execResult = onGrantedRolesToUser(Lists.newArrayList(role), userEntity);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(0L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ execResult = onGrantedRolesToGroup(Lists.newArrayList(role), groupEntity);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+ }
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ for (Role role : roles) {
+ role.securableObjects()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn("The policy is not exist for the securable object({})", securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject
+ .privileges()
+ .forEach(
+ privilege -> {
+ // Convert Gravitino privilege to Ranger privilege
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .forEach(
+ // Use the Ranger privilege name to search
+ rangerPrivilegeName -> {
+ policy
+ /**
+ * TODO: Maybe we need to add the user to the
+ * Deny/DataMask/RowFilter policy item in the future.
+ */
+ .getPolicyItems()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilegeName))) {
+ // If the user is not exist in the policy item, then
+ // add it.
+ if (!policyItem.getUsers().contains(user.name())) {
+ policyItem.getUsers().add(user.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ AtomicReference<Boolean> result = new AtomicReference<>(Boolean.TRUE);
+ for (Role role : roles) {
+ role.securableObjects()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn("The policy is not exist for the securable object({})", securableObject);
+ result.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject
+ .privileges()
+ .forEach(
+ privilege -> {
+ // Convert Gravitino privilege to Ranger privilege
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .forEach(
+ // Use the Ranger privilege name to search
+ rangerPrivilegeName -> {
+ policy
+ // TODO: Maybe we need to add the user to the
+ // Deny/DataMask/RowFilter policy item in the future.
+ .getPolicyItems()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilegeName))) {
+ // If the user is exist in the policy item, then
+ // remove it.
+ policyItem.getUsers().removeIf(user.name()::equals);
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ if (!result.get()) {
+ return Boolean.FALSE;
+ }
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ AtomicReference<Boolean> result = new AtomicReference<>(Boolean.TRUE);
+ for (Role role : roles) {
+ role.securableObjects()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn("The policy is not exist for the securable object({})", securableObject);
+ result.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject
+ .privileges()
+ .forEach(
+ privilege -> {
+ // Convert Gravitino privilege to Ranger privilege
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .forEach(
+ // Use the Ranger privilege name to search
+ rangerPrivilegeName -> {
+ policy
+ // TODO: Maybe we need to add the user to the
+ // Deny/DataMask/RowFilter policy item in the future.
+ .getPolicyItems()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilegeName))) {
+ // If the user is not exist in the policy item, then
+ // add it.
+ if (!policyItem
+ .getGroups()
+ .contains(group.name())) {
+ policyItem.getGroups().add(group.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ if (!result.get()) {
+ return Boolean.FALSE;
+ }
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ AtomicReference<Boolean> result = new AtomicReference<>(Boolean.TRUE);
+ for (Role role : roles) {
+ role.securableObjects()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn("The policy is not exist for the securable object({})", securableObject);
+ result.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject
+ .privileges()
+ .forEach(
+ privilege -> {
+ // Convert Gravitino privilege to Ranger privilege
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .forEach(
+ // Use the Ranger privilege name to search
+ rangerPrivilegeName -> {
+ policy
+ // TODO: Maybe we need to add the user to the
+ // Deny/DataMask/RowFilter policy item in the future.
+ .getPolicyItems()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilegeName))) {
+ // If the user is exist in the policy item, then
+ // remove it.
+ policyItem
+ .getGroups()
+ .removeIf(group.name()::equals);
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ if (!result.get()) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the securable object. <br>
+ * 2. If the policy is exist and have same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy is exist but have different privilege, also return true. Because one Ranger
+ * policy maybe contain multiple Gravitino securable object <br>
+ * 4. If the policy is not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(String roleName, RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If exist policy and have same privilege then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(formatPolicyName(roleName, change.getSecurableObject().fullName()));
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> metadataObjectNamespaces =
+ Lists.newArrayList(
+ SecurableObjects.DOT_SPLITTER.splitToList(change.getSecurableObject().fullName()));
+ if (metadataObjectNamespaces.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ metadataObjectNamespaces.remove(0); // remove `catalog`
Review Comment:
Ranger Hive only has `database`, `table`, and `column`, It doesn't have `catalog`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#issuecomment-2295558798
@lw-yang @yuqi1129 I refactor this PR, Please help me review it again, thanks!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724774008
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
Review Comment:
This is resolved.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#issuecomment-2301785058
Only one point:
1. Some privileges like `use schema`, `use catalog`, `create catalog` could be pushed down underlying system, too. The check logic will throw exception for them.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1726208894
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
Review Comment:
I create a issue #4620 to track this problem
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "lw-yang (via GitHub)" <gi...@apache.org>.
lw-yang commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1721691630
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1015 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
Review Comment:
If this policyItem cannot be found, should we add a new policyItem?
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1015 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+
+ role.securableObjects().stream()
Review Comment:
I think that the `grantRolesToUser` only needs to call `rangerClient.grantRole` to modify the relationship between role and user. It has nothing to do with `policy`, we shouldn't modify the `policy`.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHiveAuthorizationPlugin.java:
##########
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Set;
+import org.apache.gravitino.authorization.Privilege;
+
+/**
+ * RangerHiveAuthorizationPlugin is a plugin for Apache Ranger to manage the Hive authorization of
+ * the Apache Gravitino.
+ */
+public class RangerHiveAuthorizationPlugin extends RangerAuthorizationPlugin {
+ public RangerHiveAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super(catalogProvider, config);
+ }
+
+ /**
+ * Ranger hive's privilege have `select`, `update`, `create`, `drop`, `alter`, `index`, `lock`,
+ * `read`, `write`, `repladmin`, `serviceadmin`, `refresh` and `all`. Reference:
+ * ranger/agents-common/src/main/resources/service-defs/ranger-servicedef-hive.json
+ */
+ @Override
+ protected void initMapPrivileges() {
+ mapPrivileges =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_SELECT))
Review Comment:
Why is `CREATE_SCHEMA` mapped to `ACCESS_TYPE_HIVE_SELECT`?
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1015 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ // Find match policy item and set the role
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return execResult.get();
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
Review Comment:
like `grantRolesToUser `
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHiveAuthorizationPlugin.java:
##########
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Set;
+import org.apache.gravitino.authorization.Privilege;
+
+/**
+ * RangerHiveAuthorizationPlugin is a plugin for Apache Ranger to manage the Hive authorization of
+ * the Apache Gravitino.
+ */
+public class RangerHiveAuthorizationPlugin extends RangerAuthorizationPlugin {
+ public RangerHiveAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super(catalogProvider, config);
+ }
+
+ /**
+ * Ranger hive's privilege have `select`, `update`, `create`, `drop`, `alter`, `index`, `lock`,
+ * `read`, `write`, `repladmin`, `serviceadmin`, `refresh` and `all`. Reference:
+ * ranger/agents-common/src/main/resources/service-defs/ranger-servicedef-hive.json
+ */
+ @Override
+ protected void initMapPrivileges() {
+ mapPrivileges =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
Review Comment:
if `Privilege` is `CREATE_TABLE`, the ranger policy resource maybe is catalog.schema.*
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1015 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ // Find match policy item and set the role
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return execResult.get();
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy is not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilege -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilege))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+ return execResult.get();
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ mapAccesses.put(access.getType(), true);
+ });
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy exists but has different privileges, also return true. Because one Ranger
+ * policy maybe contain multiple Gravitino securable object <br>
+ * 4. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravition securable object's privilege
+ // and roleName
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If exist policy and have same privilege then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(change.getSecurableObject().fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(
+ SecurableObjects.DOT_SPLITTER.splitToList(change.getSecurableObject().fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+ }
+
+ addPolicyItem(policy, change.getRoleName(), change.getSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return true;
+ }
+
+ /**
+ * Remove the securable object's privilege from the policy. <br>
+ * Because Ranger use unique metadata to location Ranger policy and manage the all privileges, So
+ * one Ranger policy maybe contain multiple Gravitino privilege objects. <br>
+ * Remove Ranger policy item condition is: <br>
+ * 1. This Ranger policy item's accesses equal the Gravition securable object's privilege. <br>
+ * 2. This Ranger policy item's users and groups is empty. <br>
+ * If policy didn't have any policy item, then delete this policy: <br>
+ */
+ private boolean doRemoveSecurableObject(
+ String roleName, RoleChange.RemoveSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ policy
+ .getPolicyItems()
+ .forEach(
+ policyItem -> {
+ boolean match =
+ policyItem.getAccesses().stream()
+ .allMatch(
+ // Find the policy item that match access and role
+ access -> {
+ // Use Gravitino privilege to search the Ranger policy item's access
+ boolean matchPrivilege =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(
+ privilege ->
+ translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .anyMatch(privilege -> privilege.equals(access.getType()));
+ return matchPrivilege;
+ });
+ if (match) {
+ policyItem.getRoles().removeIf(roleName::equals);
+ }
+ });
+
+ // If the policy does have any role and user and group, then remove it.
+ policy
+ .getPolicyItems()
+ .removeIf(
+ policyItem ->
+ policyItem.getRoles().isEmpty()
+ && policyItem.getUsers().isEmpty()
+ && policyItem.getGroups().isEmpty());
+
+ try {
+ if (policy.getPolicyItems().size() == 0) {
+ rangerClient.deletePolicy(policy.getId());
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ LOG.error("Failed to remove the policy item from the Ranger policy {}!", policy);
+ throw new RuntimeException(e);
+ }
+ } else {
+ LOG.warn(
+ "Cannot find the Ranger policy({}) for the Gravitino securable object({})!",
+ roleName,
+ change.getSecurableObject().fullName());
+ // Don't throw exception or return false, because need support immutable operation.
+ }
+ return true;
+ }
+
+ /**
+ * 1. Find the policy base securable object. <br>
+ * 2. If the policy is exist, then user new securable object's privilege to update. <br>
+ * 3. If the policy is not exist return false. <br>
+ */
+ private boolean doUpdateSecurableObject(
+ String roleName, RoleChange.UpdateSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ removePolicyItem(policy, roleName, change.getSecurableObject());
+ addPolicyItem(policy, roleName, change.getNewSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ } else {
+ LOG.warn(
+ "Cannot find the policy({}) for the securable object({})!",
+ roleName,
+ change.getSecurableObject().fullName());
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Add policy item access items base the securable object's privileges. <br>
+ * We didn't clean the policy items, because one Ranger policy maybe contain multiple Gravitino
+ * securable objects. <br>
+ */
+ private void addPolicyItem(
+ RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkSecurableObject(securableObject);
+
+ // Add the policy items by the securable object's privileges
+ securableObject
+ .privileges()
+ .forEach(
+ gravitinoPrivilege -> {
+ // Translate the Gravitino privilege to mapped Ranger privilege
+ translatePrivilege(gravitinoPrivilege.name())
+ .forEach(
+ mappedPrivilege -> {
+ // Find the policy item that match access and role
+ boolean exist =
+ policy.getPolicyItems().stream()
+ .anyMatch(
+ policyItem -> {
+ return policyItem.getRoles().contains(roleName)
+ && policyItem.getAccesses().stream()
+ .anyMatch(
+ access ->
+ access.getType().equals(mappedPrivilege));
+ });
+ if (exist) {
+ return;
+ }
+
+ RangerPolicy.RangerPolicyItem policyItem =
+ new RangerPolicy.RangerPolicyItem();
+ RangerPolicy.RangerPolicyItemAccess access =
+ new RangerPolicy.RangerPolicyItemAccess();
Review Comment:
If a policy item already exists with a matching accessType and mappedPrivilege, should we update this policy item instead of continuing to create a new policy item?
We should ensure that a privilege has only one policy item to improve maintainability.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1015 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
Review Comment:
Should we verify whether the user exists in Ranger?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1722757909
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
Review Comment:
Could you handle the case?
`catalog READ_TABLE`
`metalake READ_TABLE`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1723258341
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ mapAccesses.put(access.getType(), true);
+ });
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy exists but has different privileges, also return true. Because one Ranger
+ * policy maybe contain multiple Gravitino securable object <br>
+ * 4. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravition securable object's privilege
+ // and roleName
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If exist policy and have same privilege then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(change.getSecurableObject().fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(
+ SecurableObjects.DOT_SPLITTER.splitToList(change.getSecurableObject().fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
Review Comment:
You can wrap `RangerDefines.RESOURCE_DATABASE`, `RangerDefines.RESOURCE_TABLE` and `RangerDefines.RESOURCE_COLUMN` to a list. It will make code readable.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1722779794
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHiveAuthorizationPlugin.java:
##########
@@ -0,0 +1,86 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Set;
+import org.apache.gravitino.authorization.Privilege;
+
+/**
+ * RangerHiveAuthorizationPlugin is a plugin for Apache Ranger to manage the Hive authorization of
+ * the Apache Gravitino.
+ */
+public class RangerHiveAuthorizationPlugin extends RangerAuthorizationPlugin {
+ public RangerHiveAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super(catalogProvider, config);
+ }
+
+ /**
+ * Ranger hive's privilege have `select`, `update`, `create`, `drop`, `alter`, `index`, `lock`,
+ * `read`, `write`, `repladmin`, `serviceadmin`, `refresh` and `all`. Reference:
+ * ranger/agents-common/src/main/resources/service-defs/ranger-servicedef-hive.json
+ */
+ @Override
+ protected void initMapPrivileges() {
+ mapPrivileges =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.MODIFY_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_UPDATE,
+ RangerDefines.ACCESS_TYPE_HIVE_ALTER,
+ RangerDefines.ACCESS_TYPE_HIVE_WRITE))
Review Comment:
You delete the privilege drop table. But if you have the privilege modify table. You can delete the table. Drop table is different from delete table.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1722779794
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHiveAuthorizationPlugin.java:
##########
@@ -0,0 +1,86 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Set;
+import org.apache.gravitino.authorization.Privilege;
+
+/**
+ * RangerHiveAuthorizationPlugin is a plugin for Apache Ranger to manage the Hive authorization of
+ * the Apache Gravitino.
+ */
+public class RangerHiveAuthorizationPlugin extends RangerAuthorizationPlugin {
+ public RangerHiveAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super(catalogProvider, config);
+ }
+
+ /**
+ * Ranger hive's privilege have `select`, `update`, `create`, `drop`, `alter`, `index`, `lock`,
+ * `read`, `write`, `repladmin`, `serviceadmin`, `refresh` and `all`. Reference:
+ * ranger/agents-common/src/main/resources/service-defs/ranger-servicedef-hive.json
+ */
+ @Override
+ protected void initMapPrivileges() {
+ mapPrivileges =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.MODIFY_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_UPDATE,
+ RangerDefines.ACCESS_TYPE_HIVE_ALTER,
+ RangerDefines.ACCESS_TYPE_HIVE_WRITE))
Review Comment:
You delete the privilege drop table. But if you have the privilege modify table. You can delete the table.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1722782146
##########
docs/build.gradle.kts:
##########
@@ -26,6 +26,6 @@ tasks {
}
build {
- dependsOn(lintOpenAPI)
+// dependsOn(lintOpenAPI)
Review Comment:
Why do we need this?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu closed pull request #4515: [#3963] feat(core): Apache Ranger Hive authorization pushdown
URL: https://github.com/apache/gravitino/pull/4515
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724515308
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,998 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have a Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
Review Comment:
```suggestion
// Add lost owner's privilege to the policy
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724574374
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
Review Comment:
Should we give the policyFilterKeys a better name? Maybe policyPrefixFilterKeys maybe better.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724755880
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,998 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have a Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contains multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Grant role: {} to group: {} failed!", role, group, e);
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from group: {} failed!", role, group, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users =
+ StringUtils.isEmpty(userName) ? Sets.newHashSet() : Sets.newHashSet(userName);
+ Set<String> groups =
+ StringUtils.isEmpty(groupName) ? Sets.newHashSet() : Sets.newHashSet(groupName);
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(Sets.newHashSet(roleName));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception, if the role does not exist, we will then create it.
+ LOG.warn("The role({}) is not exist in the Ranger!", roleName);
+ }
+
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manually precisely filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are managed by Gravitino.
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ mapAccesses.put(access.getType(), true);
+ });
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy exists but has different privileges, also return true. Because one Ranger
+ * policy maybe contain multiple Gravitino securable object <br>
+ * 4. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravitino securable object's privilege
+ // and roleName
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If it exists policy with the same privilege, then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(change.getSecurableObject().fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(
+ SecurableObjects.DOT_SPLITTER.splitToList(change.getSecurableObject().fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ List<String> rangerDefinesList =
+ Lists.newArrayList(
+ RangerDefines.RESOURCE_DATABASE,
+ RangerDefines.RESOURCE_TABLE,
+ RangerDefines.RESOURCE_COLUMN);
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy.getResources().put(rangerDefinesList.get(i), policyResource);
+ }
+ }
+
+ addPolicyItem(policy, change.getRoleName(), change.getSecurableObject());
+ try {
Review Comment:
This comment isn't resolved. This code is duplicate with Line 569.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724879222
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHelper.java:
##########
@@ -0,0 +1,533 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This class is a helper class for the Ranger authorization plugin. It provides the ability to
+ * manage the Ranger policies and roles.
+ */
+public class RangerHelper {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerHelper.class);
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ RangerAuthorizationPlugin rangerAuthorizationPlugin;
+
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ /** The owner privileges, the owner can do anything on the metadata object */
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise search, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, If you use `db.table` condition to search policy, the Ranger will
+ * match `db1.table1`, `db1.table2`, `db*.table*`, So we need to manually precisely filter this
+ * research results. <br>
+ * policySearchKeys: The search Ranger policy condition key defines. <br>
+ * policyPreciseFilterKeys: The precise filter Ranger search results key defines <br>
+ */
+ protected List<String> policySearchKeys = null;
+
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public RangerHelper(RangerAuthorizationPlugin rangerAuthorizationPlugin, String catalogProvider) {
+ this.rangerAuthorizationPlugin = rangerAuthorizationPlugin;
+ switch (catalogProvider) {
+ case "hive":
+ initPrivilegesMapping();
+ initOwnerPrivileges();
+ initPolicySearchKeys();
+ initPreciseFilterKeys();
+ break;
+ default:
+ throw new IllegalArgumentException(
+ "Authorization plugin unsupported catalog provider: " + catalogProvider);
+ }
+ }
+
+ /** Initial mapping Gravitino privilege name to the underlying authorization system privileges. */
+ private void initPrivilegesMapping() {
+ privilegesMapping =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.MODIFY_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_UPDATE,
+ RangerDefines.ACCESS_TYPE_HIVE_ALTER,
+ RangerDefines.ACCESS_TYPE_HIVE_WRITE))
+ .put(
+ Privilege.Name.SELECT_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_READ, RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .build();
+ }
+
+ /** Initial Owner privileges */
+ private void initOwnerPrivileges() {
+ ownerPrivileges = ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_ALL);
+ }
+
+ /** Initial Ranger policy search key defines */
+ private void initPolicySearchKeys() {
+ policySearchKeys =
+ Arrays.asList(
+ RangerDefines.SEARCH_FILTER_DATABASE,
+ RangerDefines.SEARCH_FILTER_TABLE,
+ RangerDefines.SEARCH_FILTER_COLUMN);
+ }
+
+ /** Initial precise filter key defines */
+ private void initPreciseFilterKeys() {
+ policyPreciseFilterKeys =
+ Arrays.asList(
+ RangerDefines.RESOURCE_DATABASE,
+ RangerDefines.RESOURCE_TABLE,
+ RangerDefines.RESOURCE_COLUMN);
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Set<String> setAccesses = new HashSet<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (setAccesses.contains(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ setAccesses.add(access.getType());
+ });
+ }
+
+ /**
+ * Add policy item access items base the securable object's privileges. <br>
+ * We cannot clean the policy items because one Ranger policy maybe contains multiple Gravitino
+ * securable objects. <br>
+ */
+ void addPolicyItem(RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkPrivileges(securableObject);
+
+ // Add the policy items by the securable object's privileges
+ securableObject
+ .privileges()
+ .forEach(
+ gravitinoPrivilege -> {
+ // Translate the Gravitino privilege to map Ranger privilege
+ rangerAuthorizationPlugin
+ .translatePrivilege(gravitinoPrivilege.name())
+ .forEach(
+ mappedPrivilege -> {
+ // Find the policy item that matches Gravitino privilege
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItems =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ access -> access.getType().equals(mappedPrivilege));
+ })
+ .collect(Collectors.toList());
+
+ if (matchPolicyItems.size() == 0) {
+ // If the policy item does not exist, then create a new policy item
+ RangerPolicy.RangerPolicyItem policyItem =
+ new RangerPolicy.RangerPolicyItem();
+ RangerPolicy.RangerPolicyItemAccess access =
+ new RangerPolicy.RangerPolicyItemAccess();
+ access.setType(mappedPrivilege);
+ policyItem.getAccesses().add(access);
+ policyItem.getRoles().add(roleName);
+ if (Privilege.Condition.ALLOW == gravitinoPrivilege.condition()) {
+ policy.getPolicyItems().add(policyItem);
+ } else {
+ policy.getDenyPolicyItems().add(policyItem);
+ }
+ } else {
+ // If the policy item exists, then add the role to the policy item
+ matchPolicyItems.stream()
+ .forEach(
+ policyItem -> {
+ // If the role is not in the policy item, then add it
+ if (!policyItem.getRoles().contains(roleName)) {
+ policyItem.getRoles().add(roleName);
+ }
+ });
+ }
+ });
+ });
+ }
+
+ /**
+ * Remove policy item base the securable object's privileges and role name. <br>
+ * We cannot directly clean the policy items because one Ranger policy maybe contains multiple
+ * Gravitino privilege objects. <br>
+ */
+ void removePolicyItem(RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkPrivileges(securableObject);
+
+ // Delete the policy role base the securable object's privileges
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ boolean matchPrivilege =
+ securableObject.privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(
+ privilege ->
+ rangerAuthorizationPlugin
+ .translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .anyMatch(
+ privilege -> {
+ return access.getType().equals(privilege);
+ });
+ if (matchPrivilege
+ && !policyItem.getUsers().isEmpty()
+ && !policyItem.getGroups().isEmpty()) {
+ // Not ownership policy item, then remove the role
+ policyItem.getRoles().removeIf(roleName::equals);
+ }
+ });
+ });
+
+ // Delete the policy items if the roles are empty and not ownership policy item
+ policy
+ .getPolicyItems()
+ .removeIf(
+ policyItem -> {
+ return policyItem.getRoles().isEmpty()
+ && policyItem.getUsers().isEmpty()
+ && policyItem.getGroups().isEmpty();
+ });
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param securableObject The securable object to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ private boolean checkPrivileges(SecurableObject securableObject) {
+ securableObject
+ .privileges()
+ .forEach(
+ privilege -> {
+ check(
+ privilegesMapping.containsKey(privilege.name()),
+ "This privilege %s is not supported in the Ranger hive authorization",
+ privilege.name());
+ });
+ return true;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
Review Comment:
```suggestion
Map<String, String> preciseFilters = new HashMap<>();
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1720993986
##########
api/src/main/java/org/apache/gravitino/authorization/RoleChange.java:
##########
@@ -152,4 +165,88 @@ public String toString() {
return "REMOVESECURABLEOBJECT " + securableObject;
}
}
+
+ /**
+ * A UpdateSecurableObject to update securable object's privilege from role. <br>
Review Comment:
DONE
##########
api/src/main/java/org/apache/gravitino/authorization/RoleChange.java:
##########
@@ -152,4 +165,88 @@ public String toString() {
return "REMOVESECURABLEOBJECT " + securableObject;
}
}
+
+ /**
+ * A UpdateSecurableObject to update securable object's privilege from role. <br>
+ * The securable object's metadata entity must same as new securable object's metadata entity.
+ * <br>
+ * The securable object's privilege must be different as new securable object's privilege. <br>
+ */
+ final class UpdateSecurableObject implements RoleChange {
+ private final SecurableObject securableObject;
+ private final SecurableObject newSecurableObject;
+
+ private UpdateSecurableObject(
+ SecurableObject securableObject, SecurableObject newSecurableObject) {
+ if (!securableObject.fullName().equals(newSecurableObject.fullName())) {
+ throw new IllegalArgumentException(
+ "The securable object's metadata entity must be same as new securable object's metadata entity.");
+ }
+ if (securableObject.privileges().containsAll(newSecurableObject.privileges())) {
+ throw new IllegalArgumentException(
+ "The securable object's privilege must be different as new securable object's privilege.");
+ }
+
+ this.securableObject = securableObject;
+ this.newSecurableObject = newSecurableObject;
+ }
+
+ /**
+ * Returns the securable object to be updated.
+ *
+ * @return return a securable object.
+ */
+ public SecurableObject getSecurableObject() {
+ return this.securableObject;
+ }
+
+ /**
+ * Returns the new securable object.
+ *
+ * @return return a securable object.
+ */
+ public SecurableObject getNewSecurableObject() {
+ return this.newSecurableObject;
+ }
+
+ /**
+ * Compares this UpdateSecurableObject instance with another object for equality. The comparison
+ * is based on the old securable object and new securable object.
+ *
+ * @param o The object to compare with this instance.
+ * @return true if the given object represents the same add securable object; false otherwise.
Review Comment:
DONE
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHiveAuthorizationPlugin.java:
##########
@@ -0,0 +1,854 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Privileges;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * RangerHiveAuthorizationPlugin is a plugin for Apache Ranger to manage the Hive authorization of
+ * the Apache Gravitino.
+ */
+public class RangerHiveAuthorizationPlugin extends RangerAuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerHiveAuthorizationPlugin.class);
+
+ public RangerHiveAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+ }
+
+ /**
+ * Ranger hive's privilege have `select`, `update`, `create`, `drop`, `alter`, `index`, `lock`,
+ * `read`, `write`, `repladmin`, `serviceadmin`, `refresh` and `all`.
+ *
+ * <p>Reference: ranger/agents-common/src/main/resources/service-defs/ranger-servicedef-hive.json
+ */
+ @Override
+ protected void initMapPrivileges() {
+ mapPrivileges =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.MODIFY_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_UPDATE,
+ RangerDefines.ACCESS_TYPE_HIVE_DROP,
+ RangerDefines.ACCESS_TYPE_HIVE_ALTER,
+ RangerDefines.ACCESS_TYPE_HIVE_WRITE))
+ .put(
+ Privilege.Name.SELECT_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_READ, RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .build();
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ * Reference: https://github.com/apache/gravitino/issues/4509
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @VisibleForTesting
+ public List<Privilege> getAllPrivileges() {
+ return mapPrivileges.keySet().stream().map(Privileges::allow).collect(Collectors.toList());
+ }
+
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ List<Privilege> allPrivileges = getAllPrivileges();
+
+ SecurableObject securableObjects =
+ SecurableObjects.parse(metadataObject.fullName(), metadataObject.type(), allPrivileges);
+
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentUserName())
+ .withCreateTime(Instant.now())
+ .build();
+
+ RoleEntity role =
+ RoleEntity.builder()
+ .withId(0L)
+ .withName(OWNER_ROLE_NAME)
+ .withAuditInfo(auditInfo)
+ .withSecurableObjects(Lists.newArrayList(securableObjects))
+ .build();
+
+ Boolean execResult = onRoleCreated(role);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(0L)
+ .withName(preOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ execResult = onRevokedRolesFromUser(Lists.newArrayList(role), userEntity);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(0L)
+ .withName(preOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ execResult = onRevokedRolesFromGroup(Lists.newArrayList(role), groupEntity);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(0L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ execResult = onGrantedRolesToUser(Lists.newArrayList(role), userEntity);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(0L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ execResult = onGrantedRolesToGroup(Lists.newArrayList(role), groupEntity);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+ }
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ for (Role role : roles) {
+ role.securableObjects()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn("The policy is not exist for the securable object({})", securableObject);
Review Comment:
DONE
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHiveAuthorizationPlugin.java:
##########
@@ -0,0 +1,854 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Privileges;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * RangerHiveAuthorizationPlugin is a plugin for Apache Ranger to manage the Hive authorization of
+ * the Apache Gravitino.
+ */
+public class RangerHiveAuthorizationPlugin extends RangerAuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerHiveAuthorizationPlugin.class);
+
+ public RangerHiveAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+ }
+
+ /**
+ * Ranger hive's privilege have `select`, `update`, `create`, `drop`, `alter`, `index`, `lock`,
+ * `read`, `write`, `repladmin`, `serviceadmin`, `refresh` and `all`.
+ *
+ * <p>Reference: ranger/agents-common/src/main/resources/service-defs/ranger-servicedef-hive.json
+ */
+ @Override
+ protected void initMapPrivileges() {
+ mapPrivileges =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.MODIFY_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_UPDATE,
+ RangerDefines.ACCESS_TYPE_HIVE_DROP,
+ RangerDefines.ACCESS_TYPE_HIVE_ALTER,
+ RangerDefines.ACCESS_TYPE_HIVE_WRITE))
+ .put(
+ Privilege.Name.SELECT_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_READ, RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .build();
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ * Reference: https://github.com/apache/gravitino/issues/4509
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @VisibleForTesting
+ public List<Privilege> getAllPrivileges() {
+ return mapPrivileges.keySet().stream().map(Privileges::allow).collect(Collectors.toList());
+ }
+
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ List<Privilege> allPrivileges = getAllPrivileges();
+
+ SecurableObject securableObjects =
+ SecurableObjects.parse(metadataObject.fullName(), metadataObject.type(), allPrivileges);
+
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentUserName())
+ .withCreateTime(Instant.now())
+ .build();
+
+ RoleEntity role =
+ RoleEntity.builder()
+ .withId(0L)
+ .withName(OWNER_ROLE_NAME)
+ .withAuditInfo(auditInfo)
+ .withSecurableObjects(Lists.newArrayList(securableObjects))
+ .build();
+
+ Boolean execResult = onRoleCreated(role);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(0L)
+ .withName(preOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ execResult = onRevokedRolesFromUser(Lists.newArrayList(role), userEntity);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(0L)
+ .withName(preOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ execResult = onRevokedRolesFromGroup(Lists.newArrayList(role), groupEntity);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(0L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ execResult = onGrantedRolesToUser(Lists.newArrayList(role), userEntity);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(0L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ execResult = onGrantedRolesToGroup(Lists.newArrayList(role), groupEntity);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+ }
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ for (Role role : roles) {
+ role.securableObjects()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn("The policy is not exist for the securable object({})", securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject
+ .privileges()
+ .forEach(
+ privilege -> {
+ // Convert Gravitino privilege to Ranger privilege
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .forEach(
+ // Use the Ranger privilege name to search
+ rangerPrivilegeName -> {
+ policy
+ /**
+ * TODO: Maybe we need to add the user to the
+ * Deny/DataMask/RowFilter policy item in the future.
+ */
+ .getPolicyItems()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilegeName))) {
+ // If the user is not exist in the policy item, then
+ // add it.
+ if (!policyItem.getUsers().contains(user.name())) {
+ policyItem.getUsers().add(user.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ AtomicReference<Boolean> result = new AtomicReference<>(Boolean.TRUE);
+ for (Role role : roles) {
+ role.securableObjects()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn("The policy is not exist for the securable object({})", securableObject);
+ result.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject
+ .privileges()
+ .forEach(
+ privilege -> {
+ // Convert Gravitino privilege to Ranger privilege
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .forEach(
+ // Use the Ranger privilege name to search
+ rangerPrivilegeName -> {
+ policy
+ // TODO: Maybe we need to add the user to the
+ // Deny/DataMask/RowFilter policy item in the future.
+ .getPolicyItems()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilegeName))) {
+ // If the user is exist in the policy item, then
+ // remove it.
+ policyItem.getUsers().removeIf(user.name()::equals);
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ if (!result.get()) {
Review Comment:
I already refactor these codes
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,179 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationHookException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.util.SearchFilter;
+
+/** Ranger authorization operations hooks interfaces. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+
+ /**
+ * Because UserGroupAuthorizationPlugin::onOwnerSet() interface function didn't have param Role,
+ * So we need predefine a role name
+ */
+ public static final String OWNER_ROLE_NAME = "OWNER";
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+ public static final String POLICY_ITEM_OWNER_USER = "{OWNER}";
+
+ public RangerAuthorizationPlugin() {
+ initMapPrivileges();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /** Whether this privilege is underlying permission system supported */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected static void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationHookException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public String formatPolicyName(String roleName, String securableObjectFullName) {
+ return roleName + "-" + securableObjectFullName;
Review Comment:
This is a good idea, I modified this function.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHiveAuthorizationPlugin.java:
##########
@@ -0,0 +1,854 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Privileges;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * RangerHiveAuthorizationPlugin is a plugin for Apache Ranger to manage the Hive authorization of
+ * the Apache Gravitino.
+ */
+public class RangerHiveAuthorizationPlugin extends RangerAuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerHiveAuthorizationPlugin.class);
+
+ public RangerHiveAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+ }
+
+ /**
+ * Ranger hive's privilege have `select`, `update`, `create`, `drop`, `alter`, `index`, `lock`,
+ * `read`, `write`, `repladmin`, `serviceadmin`, `refresh` and `all`.
+ *
+ * <p>Reference: ranger/agents-common/src/main/resources/service-defs/ranger-servicedef-hive.json
+ */
+ @Override
+ protected void initMapPrivileges() {
+ mapPrivileges =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.MODIFY_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_UPDATE,
+ RangerDefines.ACCESS_TYPE_HIVE_DROP,
+ RangerDefines.ACCESS_TYPE_HIVE_ALTER,
+ RangerDefines.ACCESS_TYPE_HIVE_WRITE))
+ .put(
+ Privilege.Name.SELECT_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_READ, RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .build();
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ * Reference: https://github.com/apache/gravitino/issues/4509
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @VisibleForTesting
+ public List<Privilege> getAllPrivileges() {
+ return mapPrivileges.keySet().stream().map(Privileges::allow).collect(Collectors.toList());
+ }
+
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
Review Comment:
No, This dependent underlying permission system.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHiveAuthorizationPlugin.java:
##########
@@ -0,0 +1,840 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Privileges;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * RangerHiveAuthorizationPlugin is a plugin for Apache Ranger to manage the Hive authorization of
+ * the Apache Gravitino.
+ */
+public class RangerHiveAuthorizationPlugin extends RangerAuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerHiveAuthorizationPlugin.class);
+
+ public RangerHiveAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+ }
+
+ /**
+ * Ranger hive's privilege have `select`, `update`, `create`, `drop`, `alter`, `index`, `lock`,
+ * `read`, `write`, `repladmin`, `serviceadmin`, `refresh` and `all`.
+ *
+ * <p>Reference: ranger/agents-common/src/main/resources/service-defs/ranger-servicedef-hive.json
+ */
+ @Override
+ protected void initMapPrivileges() {
+ mapPrivileges =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(Privilege.Name.CREATE_SCHEMA, ImmutableSet.of("create"))
+ .put(Privilege.Name.CREATE_TABLE, ImmutableSet.of("create"))
+ .put(Privilege.Name.MODIFY_TABLE, ImmutableSet.of("update", "drop", "alter", "write"))
+ .put(Privilege.Name.SELECT_TABLE, ImmutableSet.of("read", "select"))
+ .build();
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
Review Comment:
Thank you for the suggestion, I refactor this PR.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHiveAuthorizationPlugin.java:
##########
@@ -0,0 +1,854 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Privileges;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * RangerHiveAuthorizationPlugin is a plugin for Apache Ranger to manage the Hive authorization of
+ * the Apache Gravitino.
+ */
+public class RangerHiveAuthorizationPlugin extends RangerAuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerHiveAuthorizationPlugin.class);
+
+ public RangerHiveAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+ }
+
+ /**
+ * Ranger hive's privilege have `select`, `update`, `create`, `drop`, `alter`, `index`, `lock`,
+ * `read`, `write`, `repladmin`, `serviceadmin`, `refresh` and `all`.
+ *
+ * <p>Reference: ranger/agents-common/src/main/resources/service-defs/ranger-servicedef-hive.json
+ */
+ @Override
+ protected void initMapPrivileges() {
+ mapPrivileges =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.MODIFY_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_UPDATE,
+ RangerDefines.ACCESS_TYPE_HIVE_DROP,
+ RangerDefines.ACCESS_TYPE_HIVE_ALTER,
+ RangerDefines.ACCESS_TYPE_HIVE_WRITE))
+ .put(
+ Privilege.Name.SELECT_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_READ, RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .build();
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ * Reference: https://github.com/apache/gravitino/issues/4509
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @VisibleForTesting
+ public List<Privilege> getAllPrivileges() {
+ return mapPrivileges.keySet().stream().map(Privileges::allow).collect(Collectors.toList());
+ }
+
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ List<Privilege> allPrivileges = getAllPrivileges();
+
+ SecurableObject securableObjects =
+ SecurableObjects.parse(metadataObject.fullName(), metadataObject.type(), allPrivileges);
+
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentUserName())
+ .withCreateTime(Instant.now())
+ .build();
+
+ RoleEntity role =
+ RoleEntity.builder()
+ .withId(0L)
+ .withName(OWNER_ROLE_NAME)
+ .withAuditInfo(auditInfo)
+ .withSecurableObjects(Lists.newArrayList(securableObjects))
+ .build();
+
+ Boolean execResult = onRoleCreated(role);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(0L)
+ .withName(preOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ execResult = onRevokedRolesFromUser(Lists.newArrayList(role), userEntity);
+ if (!execResult) {
+ return Boolean.FALSE;
Review Comment:
I already refactor these codes
##########
authorizations/authorization-ranger/build.gradle.kts:
##########
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+description = "authorization-ranger"
+
+plugins {
+ `maven-publish`
+ id("java")
+ id("idea")
+}
+
+dependencies {
+ implementation(project(":api"))
Review Comment:
DONE
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHiveAuthorizationPlugin.java:
##########
@@ -0,0 +1,854 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Privileges;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * RangerHiveAuthorizationPlugin is a plugin for Apache Ranger to manage the Hive authorization of
+ * the Apache Gravitino.
+ */
+public class RangerHiveAuthorizationPlugin extends RangerAuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerHiveAuthorizationPlugin.class);
+
+ public RangerHiveAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+ }
+
+ /**
+ * Ranger hive's privilege have `select`, `update`, `create`, `drop`, `alter`, `index`, `lock`,
+ * `read`, `write`, `repladmin`, `serviceadmin`, `refresh` and `all`.
+ *
+ * <p>Reference: ranger/agents-common/src/main/resources/service-defs/ranger-servicedef-hive.json
+ */
+ @Override
+ protected void initMapPrivileges() {
+ mapPrivileges =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.MODIFY_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_UPDATE,
+ RangerDefines.ACCESS_TYPE_HIVE_DROP,
+ RangerDefines.ACCESS_TYPE_HIVE_ALTER,
+ RangerDefines.ACCESS_TYPE_HIVE_WRITE))
+ .put(
+ Privilege.Name.SELECT_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_READ, RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .build();
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ * Reference: https://github.com/apache/gravitino/issues/4509
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
Review Comment:
I refactor these codes.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724857748
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,583 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.authorization.ranger.reference.VXGroup;
+import org.apache.gravitino.authorization.ranger.reference.VXGroupList;
+import org.apache.gravitino.authorization.ranger.reference.VXUser;
+import org.apache.gravitino.authorization.ranger.reference.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Ranger authorization operations plugin abstract class. <br>
+ * 1. For Ranger limit, The same metadata object only has a unique Ranger policy, So a Ranger policy
+ * maybe contains multiple Gravitino securable objects. <br>
+ * 2. For easy management, each Ranger privilege will create one RangerPolicyItemAccess in the
+ * policy. <br>
+ * 3. Ranger also have Role concept, and support adds multiple users or groups in the Ranger Role,
+ * So we can use the Ranger Role to implement the Gravitino Role. <br>
+ * 4. The Ranger policy also supports multiple users and groups, But we only use a user or group to
+ * implement Gravitino Owner concept. <br>
+ */
+public class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected String rangerServiceName;
+ protected RangerClientExtend rangerClient;
+ private RangerHelper rangerHelper;
+ @VisibleForTesting public final String rangerAdminName;
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ rangerAdminName = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ RangerHelper.check(rangerUrl != null, "Ranger admin URL is required");
+ RangerHelper.check(authType != null, "Ranger auth type is required");
+ RangerHelper.check(rangerAdminName != null, "Ranger username is required");
+ RangerHelper.check(password != null, "Ranger password is required");
+ RangerHelper.check(rangerServiceName != null, "Ranger service name is required");
+ rangerClient = new RangerClientExtend(rangerUrl, authType, rangerAdminName, password);
+ rangerHelper = new RangerHelper(this, catalogProvider);
+ }
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return rangerHelper.privilegesMapping.get(name);
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(rangerHelper.ownerPrivileges);
+ }
+
+ /**
+ * Create a new role in the Ranger. <br>
+ * 1. Create a policy for metadata object. <br>
+ * 2. Save role name in the Policy items. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ return rangerHelper.checkRangerRole(role.name());
+ }
+
+ /** Remove the role name from the Ranger policy item, and delete this Role in the Ranger. <br> */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, delete the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), rangerAdminName, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult = doRemoveSecurableObject((RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult = doUpdateSecurableObject((RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ * 1. If the metadata object already has an owner, then transfer the ownership from preOwner to
+ * newOwner, The function params preOwner and newOwner don't equal null. <br>
+ * 2. If the metadata object doesn't have an owner, then set the owner to newOwner, The function
+ * params preOwner equal null and newOwner don't equal null. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object.
+ * @param newOwner The new owner of the metadata object.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ RangerHelper.check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = rangerHelper.findManagedPolicy(metadataObject);
+ try {
+ if (policy == null) {
+ policy = rangerHelper.addOwnerToNewPolicy(metadataObject, newOwner);
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerHelper.updatePolicyOwner(policy, preOwner, newOwner);
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this user to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param user The user to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role: {} to user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this user from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param user The user to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
Review Comment:
If this Role doesn't exist the `checkRangerRole()` will throw exception to terminate the operation.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724849823
##########
authorizations/authorization-ranger/src/main/resources/META-INF/services/org.apache.gravitino.connector.authorization.AuthorizationProvider:
##########
@@ -0,0 +1,19 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+org.apache.gravitino.authorization.ranger.RangerAuthorization
Review Comment:
We can add multiple Authorization in the `authorization.AuthorizationProvider`, just like
https://github.com/apache/gravitino/blob/main/core/src/test/resources/META-INF/services/org.apache.gravitino.connector.authorization.AuthorizationProvider#L19
Look more carefully before you jump to conclusions!!!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724903813
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,583 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.authorization.ranger.reference.VXGroup;
+import org.apache.gravitino.authorization.ranger.reference.VXGroupList;
+import org.apache.gravitino.authorization.ranger.reference.VXUser;
+import org.apache.gravitino.authorization.ranger.reference.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Ranger authorization operations plugin abstract class. <br>
+ * 1. For Ranger limit, The same metadata object only has a unique Ranger policy, So a Ranger policy
+ * maybe contains multiple Gravitino securable objects. <br>
+ * 2. For easy management, each Ranger privilege will create one RangerPolicyItemAccess in the
+ * policy. <br>
+ * 3. Ranger also have Role concept, and support adds multiple users or groups in the Ranger Role,
+ * So we can use the Ranger Role to implement the Gravitino Role. <br>
+ * 4. The Ranger policy also supports multiple users and groups, But we only use a user or group to
+ * implement Gravitino Owner concept. <br>
+ */
+public class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected String rangerServiceName;
+ protected RangerClientExtend rangerClient;
+ private RangerHelper rangerHelper;
+ @VisibleForTesting public final String rangerAdminName;
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ rangerAdminName = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ RangerHelper.check(rangerUrl != null, "Ranger admin URL is required");
+ RangerHelper.check(authType != null, "Ranger auth type is required");
+ RangerHelper.check(rangerAdminName != null, "Ranger username is required");
+ RangerHelper.check(password != null, "Ranger password is required");
+ RangerHelper.check(rangerServiceName != null, "Ranger service name is required");
+ rangerClient = new RangerClientExtend(rangerUrl, authType, rangerAdminName, password);
+ rangerHelper = new RangerHelper(this, catalogProvider);
+ }
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return rangerHelper.privilegesMapping.get(name);
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(rangerHelper.ownerPrivileges);
+ }
+
+ /**
+ * Create a new role in the Ranger. <br>
+ * 1. Create a policy for metadata object. <br>
+ * 2. Save role name in the Policy items. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ return rangerHelper.checkRangerRole(role.name());
+ }
+
+ /** Remove the role name from the Ranger policy item, and delete this Role in the Ranger. <br> */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, delete the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), rangerAdminName, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult = doRemoveSecurableObject((RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult = doUpdateSecurableObject((RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ * 1. If the metadata object already has an owner, then transfer the ownership from preOwner to
+ * newOwner, The function params preOwner and newOwner don't equal null. <br>
+ * 2. If the metadata object doesn't have an owner, then set the owner to newOwner, The function
+ * params preOwner equal null and newOwner don't equal null. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object.
+ * @param newOwner The new owner of the metadata object.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ RangerHelper.check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = rangerHelper.findManagedPolicy(metadataObject);
+ try {
+ if (policy == null) {
+ policy = rangerHelper.addOwnerToNewPolicy(metadataObject, newOwner);
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerHelper.updatePolicyOwner(policy, preOwner, newOwner);
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this user to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param user The user to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role: {} to user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this user from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param user The user to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
Review Comment:
1. I want to know if the value of the role is null means the role does not exist or something else.
2. If the role could not be null, so I don't think we should keep the logic.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#issuecomment-2298226516
I call the method ownerSet, you can see https://github.com/qqqttt123/gravitino/commit/9203ef44e9aaef63d9a5ff91ab8e73850b7faa3b
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1723289584
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ mapAccesses.put(access.getType(), true);
+ });
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy exists but has different privileges, also return true. Because one Ranger
+ * policy maybe contain multiple Gravitino securable object <br>
+ * 4. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravition securable object's privilege
+ // and roleName
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If exist policy and have same privilege then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(change.getSecurableObject().fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(
+ SecurableObjects.DOT_SPLITTER.splitToList(change.getSecurableObject().fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+ }
+
+ addPolicyItem(policy, change.getRoleName(), change.getSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return true;
+ }
+
+ /**
+ * Remove the securable object's privilege from the policy. <br>
+ * Because Ranger use unique metadata to location Ranger policy and manage the all privileges, So
+ * one Ranger policy maybe contain multiple Gravitino privilege objects. <br>
Review Comment:
```suggestion
* A Ranger policy maybe contains multiple Gravitino privilege objects. <br>
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724349879
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
Review Comment:
Add more comments about this class.
1. What's precise filter.
2. How to map the securable object to policies.
We should give a rough mind about this class.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724574374
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
Review Comment:
Should we give the policyFilterKeys a better name?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724534814
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,998 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have a Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contains multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Grant role: {} to group: {} failed!", role, group, e);
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from group: {} failed!", role, group, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users =
+ StringUtils.isEmpty(userName) ? Sets.newHashSet() : Sets.newHashSet(userName);
+ Set<String> groups =
+ StringUtils.isEmpty(groupName) ? Sets.newHashSet() : Sets.newHashSet(groupName);
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(Sets.newHashSet(roleName));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception, if the role does not exist, we will then create it.
+ LOG.warn("The role({}) is not exist in the Ranger!", roleName);
+ }
+
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manually precisely filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are managed by Gravitino.
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
Review Comment:
Maybe you should use set here.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724525054
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,998 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have a Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contains multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Grant role: {} to group: {} failed!", role, group, e);
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from group: {} failed!", role, group, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
Review Comment:
Maybe this method should use void as return value.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724520020
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,998 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have a Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contains multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
Review Comment:
Do you need to judge the return value?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724517579
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,998 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have a Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
Review Comment:
Could you use `RangerDefines.RESOURCE_DATABASE`, `RangerDefines.RESOURCE_TABLE`, `RangerDefines.RESOURCE_COLUMN` to an array?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724887242
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,583 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.authorization.ranger.reference.VXGroup;
+import org.apache.gravitino.authorization.ranger.reference.VXGroupList;
+import org.apache.gravitino.authorization.ranger.reference.VXUser;
+import org.apache.gravitino.authorization.ranger.reference.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Ranger authorization operations plugin abstract class. <br>
+ * 1. For Ranger limit, The same metadata object only has a unique Ranger policy, So a Ranger policy
+ * maybe contains multiple Gravitino securable objects. <br>
+ * 2. For easy management, each Ranger privilege will create one RangerPolicyItemAccess in the
+ * policy. <br>
+ * 3. Ranger also have Role concept, and support adds multiple users or groups in the Ranger Role,
+ * So we can use the Ranger Role to implement the Gravitino Role. <br>
+ * 4. The Ranger policy also supports multiple users and groups, But we only use a user or group to
+ * implement Gravitino Owner concept. <br>
+ */
+public class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected String rangerServiceName;
+ protected RangerClientExtend rangerClient;
+ private RangerHelper rangerHelper;
+ @VisibleForTesting public final String rangerAdminName;
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ rangerAdminName = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ RangerHelper.check(rangerUrl != null, "Ranger admin URL is required");
+ RangerHelper.check(authType != null, "Ranger auth type is required");
+ RangerHelper.check(rangerAdminName != null, "Ranger username is required");
+ RangerHelper.check(password != null, "Ranger password is required");
+ RangerHelper.check(rangerServiceName != null, "Ranger service name is required");
+ rangerClient = new RangerClientExtend(rangerUrl, authType, rangerAdminName, password);
+ rangerHelper = new RangerHelper(this, catalogProvider);
+ }
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return rangerHelper.privilegesMapping.get(name);
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(rangerHelper.ownerPrivileges);
+ }
+
+ /**
+ * Create a new role in the Ranger. <br>
+ * 1. Create a policy for metadata object. <br>
+ * 2. Save role name in the Policy items. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ return rangerHelper.checkRangerRole(role.name());
+ }
+
+ /** Remove the role name from the Ranger policy item, and delete this Role in the Ranger. <br> */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, delete the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), rangerAdminName, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult = doRemoveSecurableObject((RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult = doUpdateSecurableObject((RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ * 1. If the metadata object already has an owner, then transfer the ownership from preOwner to
+ * newOwner, The function params preOwner and newOwner don't equal null. <br>
+ * 2. If the metadata object doesn't have an owner, then set the owner to newOwner, The function
+ * params preOwner equal null and newOwner don't equal null. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object.
+ * @param newOwner The new owner of the metadata object.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ RangerHelper.check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = rangerHelper.findManagedPolicy(metadataObject);
+ try {
+ if (policy == null) {
+ policy = rangerHelper.addOwnerToNewPolicy(metadataObject, newOwner);
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerHelper.updatePolicyOwner(policy, preOwner, newOwner);
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this user to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param user The user to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role: {} to user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this user from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param user The user to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this group to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Grant role: {} to group: {} failed!", role, group, e);
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this group from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param group The group to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from group: {} failed!", role, group, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) already exists in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) doesn't exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) doesn't exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) doesn't exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) doesn't exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Add the securable object's privilege to the Ranger policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = rangerHelper.findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravitino securable object's privilege
+ Set<String> policyPrivileges =
Review Comment:
Could we reuse the method mappingPrivilege here?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724882507
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHelper.java:
##########
@@ -0,0 +1,533 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This class is a helper class for the Ranger authorization plugin. It provides the ability to
+ * manage the Ranger policies and roles.
+ */
+public class RangerHelper {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerHelper.class);
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ RangerAuthorizationPlugin rangerAuthorizationPlugin;
+
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ /** The owner privileges, the owner can do anything on the metadata object */
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise search, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, If you use `db.table` condition to search policy, the Ranger will
+ * match `db1.table1`, `db1.table2`, `db*.table*`, So we need to manually precisely filter this
+ * research results. <br>
+ * policySearchKeys: The search Ranger policy condition key defines. <br>
+ * policyPreciseFilterKeys: The precise filter Ranger search results key defines <br>
+ */
+ protected List<String> policySearchKeys = null;
+
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public RangerHelper(RangerAuthorizationPlugin rangerAuthorizationPlugin, String catalogProvider) {
+ this.rangerAuthorizationPlugin = rangerAuthorizationPlugin;
+ switch (catalogProvider) {
+ case "hive":
+ initPrivilegesMapping();
+ initOwnerPrivileges();
+ initPolicySearchKeys();
+ initPreciseFilterKeys();
+ break;
+ default:
+ throw new IllegalArgumentException(
+ "Authorization plugin unsupported catalog provider: " + catalogProvider);
+ }
+ }
+
+ /** Initial mapping Gravitino privilege name to the underlying authorization system privileges. */
+ private void initPrivilegesMapping() {
+ privilegesMapping =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.MODIFY_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_UPDATE,
+ RangerDefines.ACCESS_TYPE_HIVE_ALTER,
+ RangerDefines.ACCESS_TYPE_HIVE_WRITE))
+ .put(
+ Privilege.Name.SELECT_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_READ, RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .build();
+ }
+
+ /** Initial Owner privileges */
+ private void initOwnerPrivileges() {
+ ownerPrivileges = ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_ALL);
+ }
+
+ /** Initial Ranger policy search key defines */
+ private void initPolicySearchKeys() {
+ policySearchKeys =
+ Arrays.asList(
+ RangerDefines.SEARCH_FILTER_DATABASE,
+ RangerDefines.SEARCH_FILTER_TABLE,
+ RangerDefines.SEARCH_FILTER_COLUMN);
+ }
+
+ /** Initial precise filter key defines */
+ private void initPreciseFilterKeys() {
+ policyPreciseFilterKeys =
+ Arrays.asList(
+ RangerDefines.RESOURCE_DATABASE,
+ RangerDefines.RESOURCE_TABLE,
+ RangerDefines.RESOURCE_COLUMN);
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Set<String> setAccesses = new HashSet<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (setAccesses.contains(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ setAccesses.add(access.getType());
+ });
+ }
+
+ /**
+ * Add policy item access items base the securable object's privileges. <br>
+ * We didn't clean the policy items because one Ranger policy maybe contains multiple Gravitino
+ * securable objects. <br>
+ */
+ void addPolicyItem(RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkPrivileges(securableObject);
+
+ // Add the policy items by the securable object's privileges
+ securableObject
+ .privileges()
+ .forEach(
+ gravitinoPrivilege -> {
+ // Translate the Gravitino privilege to map Ranger privilege
+ rangerAuthorizationPlugin
+ .translatePrivilege(gravitinoPrivilege.name())
+ .forEach(
+ mappedPrivilege -> {
Review Comment:
It can reuse some code at least.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724884494
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHelper.java:
##########
@@ -0,0 +1,533 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This class is a helper class for the Ranger authorization plugin. It provides the ability to
+ * manage the Ranger policies and roles.
+ */
+public class RangerHelper {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerHelper.class);
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ RangerAuthorizationPlugin rangerAuthorizationPlugin;
+
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ /** The owner privileges, the owner can do anything on the metadata object */
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise search, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, If you use `db.table` condition to search policy, the Ranger will
+ * match `db1.table1`, `db1.table2`, `db*.table*`, So we need to manually precisely filter this
+ * research results. <br>
+ * policySearchKeys: The search Ranger policy condition key defines. <br>
+ * policyPreciseFilterKeys: The precise filter Ranger search results key defines <br>
+ */
+ protected List<String> policySearchKeys = null;
+
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public RangerHelper(RangerAuthorizationPlugin rangerAuthorizationPlugin, String catalogProvider) {
+ this.rangerAuthorizationPlugin = rangerAuthorizationPlugin;
+ switch (catalogProvider) {
+ case "hive":
+ initPrivilegesMapping();
+ initOwnerPrivileges();
+ initPolicySearchKeys();
+ initPreciseFilterKeys();
+ break;
+ default:
+ throw new IllegalArgumentException(
+ "Authorization plugin unsupported catalog provider: " + catalogProvider);
+ }
+ }
+
+ /** Initial mapping Gravitino privilege name to the underlying authorization system privileges. */
+ private void initPrivilegesMapping() {
+ privilegesMapping =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.MODIFY_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_UPDATE,
+ RangerDefines.ACCESS_TYPE_HIVE_ALTER,
+ RangerDefines.ACCESS_TYPE_HIVE_WRITE))
+ .put(
+ Privilege.Name.SELECT_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_READ, RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .build();
+ }
+
+ /** Initial Owner privileges */
+ private void initOwnerPrivileges() {
+ ownerPrivileges = ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_ALL);
+ }
+
+ /** Initial Ranger policy search key defines */
+ private void initPolicySearchKeys() {
+ policySearchKeys =
+ Arrays.asList(
+ RangerDefines.SEARCH_FILTER_DATABASE,
+ RangerDefines.SEARCH_FILTER_TABLE,
+ RangerDefines.SEARCH_FILTER_COLUMN);
+ }
+
+ /** Initial precise filter key defines */
+ private void initPreciseFilterKeys() {
+ policyPreciseFilterKeys =
+ Arrays.asList(
+ RangerDefines.RESOURCE_DATABASE,
+ RangerDefines.RESOURCE_TABLE,
+ RangerDefines.RESOURCE_COLUMN);
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Set<String> setAccesses = new HashSet<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (setAccesses.contains(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ setAccesses.add(access.getType());
+ });
+ }
+
+ /**
+ * Add policy item access items base the securable object's privileges. <br>
+ * We cannot clean the policy items because one Ranger policy maybe contains multiple Gravitino
+ * securable objects. <br>
+ */
+ void addPolicyItem(RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkPrivileges(securableObject);
+
+ // Add the policy items by the securable object's privileges
+ securableObject
+ .privileges()
+ .forEach(
+ gravitinoPrivilege -> {
+ // Translate the Gravitino privilege to map Ranger privilege
+ rangerAuthorizationPlugin
+ .translatePrivilege(gravitinoPrivilege.name())
+ .forEach(
+ mappedPrivilege -> {
+ // Find the policy item that matches Gravitino privilege
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItems =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ access -> access.getType().equals(mappedPrivilege));
+ })
+ .collect(Collectors.toList());
+
+ if (matchPolicyItems.size() == 0) {
+ // If the policy item does not exist, then create a new policy item
+ RangerPolicy.RangerPolicyItem policyItem =
+ new RangerPolicy.RangerPolicyItem();
+ RangerPolicy.RangerPolicyItemAccess access =
+ new RangerPolicy.RangerPolicyItemAccess();
+ access.setType(mappedPrivilege);
+ policyItem.getAccesses().add(access);
+ policyItem.getRoles().add(roleName);
+ if (Privilege.Condition.ALLOW == gravitinoPrivilege.condition()) {
+ policy.getPolicyItems().add(policyItem);
+ } else {
+ policy.getDenyPolicyItems().add(policyItem);
+ }
+ } else {
+ // If the policy item exists, then add the role to the policy item
+ matchPolicyItems.stream()
+ .forEach(
+ policyItem -> {
+ // If the role is not in the policy item, then add it
+ if (!policyItem.getRoles().contains(roleName)) {
+ policyItem.getRoles().add(roleName);
+ }
+ });
+ }
+ });
+ });
+ }
+
+ /**
+ * Remove policy item base the securable object's privileges and role name. <br>
+ * We cannot directly clean the policy items because one Ranger policy maybe contains multiple
+ * Gravitino privilege objects. <br>
+ */
+ void removePolicyItem(RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkPrivileges(securableObject);
+
+ // Delete the policy role base the securable object's privileges
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ boolean matchPrivilege =
+ securableObject.privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(
+ privilege ->
+ rangerAuthorizationPlugin
+ .translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .anyMatch(
+ privilege -> {
+ return access.getType().equals(privilege);
+ });
+ if (matchPrivilege
+ && !policyItem.getUsers().isEmpty()
Review Comment:
Why do we need `getUsers` is empty and `getGroups` is empty?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724888182
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,583 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.authorization.ranger.reference.VXGroup;
+import org.apache.gravitino.authorization.ranger.reference.VXGroupList;
+import org.apache.gravitino.authorization.ranger.reference.VXUser;
+import org.apache.gravitino.authorization.ranger.reference.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Ranger authorization operations plugin abstract class. <br>
+ * 1. For Ranger limit, The same metadata object only has a unique Ranger policy, So a Ranger policy
+ * maybe contains multiple Gravitino securable objects. <br>
+ * 2. For easy management, each Ranger privilege will create one RangerPolicyItemAccess in the
+ * policy. <br>
+ * 3. Ranger also have Role concept, and support adds multiple users or groups in the Ranger Role,
+ * So we can use the Ranger Role to implement the Gravitino Role. <br>
+ * 4. The Ranger policy also supports multiple users and groups, But we only use a user or group to
+ * implement Gravitino Owner concept. <br>
+ */
+public class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected String rangerServiceName;
+ protected RangerClientExtend rangerClient;
+ private RangerHelper rangerHelper;
+ @VisibleForTesting public final String rangerAdminName;
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ rangerAdminName = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ RangerHelper.check(rangerUrl != null, "Ranger admin URL is required");
+ RangerHelper.check(authType != null, "Ranger auth type is required");
+ RangerHelper.check(rangerAdminName != null, "Ranger username is required");
+ RangerHelper.check(password != null, "Ranger password is required");
+ RangerHelper.check(rangerServiceName != null, "Ranger service name is required");
+ rangerClient = new RangerClientExtend(rangerUrl, authType, rangerAdminName, password);
+ rangerHelper = new RangerHelper(this, catalogProvider);
+ }
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return rangerHelper.privilegesMapping.get(name);
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(rangerHelper.ownerPrivileges);
+ }
+
+ /**
+ * Create a new role in the Ranger. <br>
+ * 1. Create a policy for metadata object. <br>
+ * 2. Save role name in the Policy items. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ return rangerHelper.checkRangerRole(role.name());
+ }
+
+ /** Remove the role name from the Ranger policy item, and delete this Role in the Ranger. <br> */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, delete the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), rangerAdminName, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult = doRemoveSecurableObject((RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult = doUpdateSecurableObject((RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ * 1. If the metadata object already has an owner, then transfer the ownership from preOwner to
+ * newOwner, The function params preOwner and newOwner don't equal null. <br>
+ * 2. If the metadata object doesn't have an owner, then set the owner to newOwner, The function
+ * params preOwner equal null and newOwner don't equal null. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object.
+ * @param newOwner The new owner of the metadata object.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ RangerHelper.check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = rangerHelper.findManagedPolicy(metadataObject);
+ try {
+ if (policy == null) {
+ policy = rangerHelper.addOwnerToNewPolicy(metadataObject, newOwner);
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerHelper.updatePolicyOwner(policy, preOwner, newOwner);
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this user to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param user The user to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role: {} to user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this user from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param user The user to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this group to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Grant role: {} to group: {} failed!", role, group, e);
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this group from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param group The group to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from group: {} failed!", role, group, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) already exists in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) doesn't exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) doesn't exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) doesn't exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) doesn't exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Add the securable object's privilege to the Ranger policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = rangerHelper.findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravitino securable object's privilege
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If it exists policy with the same privilege, then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(change.getSecurableObject().fullName());
+ policy.setPolicyLabels(Lists.newArrayList(RangerHelper.MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(
+ SecurableObjects.DOT_SPLITTER.splitToList(change.getSecurableObject().fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ List<String> rangerDefinesList =
+ Lists.newArrayList(
+ RangerDefines.RESOURCE_DATABASE,
+ RangerDefines.RESOURCE_TABLE,
+ RangerDefines.RESOURCE_COLUMN);
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy.getResources().put(rangerDefinesList.get(i), policyResource);
+ }
+ }
+
+ rangerHelper.addPolicyItem(policy, change.getRoleName(), change.getSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return true;
+ }
+
+ /**
+ * Remove the securable object's privilege from the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, then remove role name in the policy items.
+ * <br>
+ * 3. If policy does not contain any policy item, then delete this policy. <br>
+ */
+ private boolean doRemoveSecurableObject(RoleChange.RemoveSecurableObject change) {
+ RangerPolicy policy = rangerHelper.findManagedPolicy(change.getSecurableObject());
+ if (policy == null) {
+ LOG.warn(
+ "Cannot find the Ranger policy({}) for the Gravitino securable object({})!",
+ change.getRoleName(),
+ change.getSecurableObject().fullName());
+ // Don't throw exception or return false, because need support immutable operation.
+ return true;
+ }
+
+ policy
+ .getPolicyItems()
+ .forEach(
+ policyItem -> {
+ boolean match =
+ policyItem.getAccesses().stream()
+ .allMatch(
+ // Find the policy item that matches access and role
+ access -> {
+ // Use Gravitino privilege to search the Ranger policy item's access
+ boolean matchPrivilege =
Review Comment:
Could we reuse method `mappingPrivilege` here?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1720960360
##########
api/src/main/java/org/apache/gravitino/authorization/RoleChange.java:
##########
@@ -152,4 +165,88 @@ public String toString() {
return "REMOVESECURABLEOBJECT " + securableObject;
}
}
+
+ /**
+ * A UpdateSecurableObject to update securable object's privilege from role. <br>
+ * The securable object's metadata entity must same as new securable object's metadata entity.
Review Comment:
DONE.
##########
api/src/main/java/org/apache/gravitino/authorization/RoleChange.java:
##########
@@ -152,4 +165,88 @@ public String toString() {
return "REMOVESECURABLEOBJECT " + securableObject;
}
}
+
+ /**
+ * A UpdateSecurableObject to update securable object's privilege from role. <br>
+ * The securable object's metadata entity must same as new securable object's metadata entity.
+ * <br>
+ * The securable object's privilege must be different as new securable object's privilege. <br>
+ */
+ final class UpdateSecurableObject implements RoleChange {
+ private final SecurableObject securableObject;
+ private final SecurableObject newSecurableObject;
+
+ private UpdateSecurableObject(
+ SecurableObject securableObject, SecurableObject newSecurableObject) {
+ if (!securableObject.fullName().equals(newSecurableObject.fullName())) {
+ throw new IllegalArgumentException(
+ "The securable object's metadata entity must be same as new securable object's metadata entity.");
+ }
+ if (securableObject.privileges().containsAll(newSecurableObject.privileges())) {
+ throw new IllegalArgumentException(
+ "The securable object's privilege must be different as new securable object's privilege.");
Review Comment:
DONE
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1723250966
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
Review Comment:
Modify the comments.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1723041477
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
Review Comment:
OK
##########
docs/build.gradle.kts:
##########
@@ -26,6 +26,6 @@ tasks {
}
build {
- dependsOn(lintOpenAPI)
+// dependsOn(lintOpenAPI)
Review Comment:
I forgot rollback this change.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1721258547
##########
authorizations/authorization-ranger/build.gradle.kts:
##########
@@ -0,0 +1,113 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+description = "authorization-ranger"
+
+plugins {
+ `maven-publish`
+ id("java")
+ id("idea")
+}
+
+dependencies {
+ implementation(project(":api")) {
+ exclude(group = "*")
+ }
+ implementation(project(":core"))
Review Comment:
You also need to exclude all dependencies of `core`.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
Review Comment:
When was this variant used and what is it used for?
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
Review Comment:
We'd better add some logs to indicate whether the request was successful or not , as we ignore exceptions completely.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ if (!policyItem
Review Comment:
1. Merge excessive If sentence.
2. Could you please break down the method into several smaller components?
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy is not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilege -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilege))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+
+ return Boolean.TRUE;
Review Comment:
```suggestion
return execResult.get();
```
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy is not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilege -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilege))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role is not exist. */
+ private RangerRole createRangerRole(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role is not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
Review Comment:
Please remove this annotation as it is NOT used by tests only.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy is not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilege -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilege))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role is not exist. */
+ private RangerRole createRangerRole(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role is not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
Review Comment:
```suggestion
if (policies.isEmpty()) {
return null;
}
RangerPolicy policy = policies.get(0);
policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
return policy;
```
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy is not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilege -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilege))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role is not exist. */
+ private RangerRole createRangerRole(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role is not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy manage, each privilege will create a RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege in the delegate Gravitino management policy ");
Review Comment:
Please add the duplicated policy name or something else to the error message to make it clearer for users.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy is not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilege -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilege))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role is not exist. */
+ private RangerRole createRangerRole(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role is not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy manage, each privilege will create a RangerPolicyItemAccess in the policy.
Review Comment:
manage -> management.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy is not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilege -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilege))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role is not exist. */
+ private RangerRole createRangerRole(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role is not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy manage, each privilege will create a RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
Review Comment:
Can the size of `policyItem.getAccesses()` be empty?
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy is not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilege -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilege))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role is not exist. */
+ private RangerRole createRangerRole(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role is not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy manage, each privilege will create a RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege in the delegate Gravitino management policy ");
+ }
+ mapAccesses.put(access.getType(), true);
+ });
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
Review Comment:
also polish the comment for example
If the policy exists and has the same privilege, the method will return true since it supports the idempotent operation.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy is not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilege -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilege))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role is not exist. */
+ private RangerRole createRangerRole(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role is not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy manage, each privilege will create a RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege in the delegate Gravitino management policy ");
+ }
+ mapAccesses.put(access.getType(), true);
+ });
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy is exist and have same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy is exist but have different privilege, also return true. Because one Ranger
+ * policy maybe contain multiple Gravitino securable object <br>
+ * 4. If the policy is not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravition securable object's privilege
+ // and roleName
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If exist policy and have same privilege then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
Review Comment:
Remove this else block to reduce nesting.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy is not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilege -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilege))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role is not exist. */
+ private RangerRole createRangerRole(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role is not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy manage, each privilege will create a RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege in the delegate Gravitino management policy ");
+ }
+ mapAccesses.put(access.getType(), true);
+ });
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
Review Comment:
Please change `is exist` -> `exist`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1721675565
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHiveAuthorizationPlugin.java:
##########
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Set;
+import org.apache.gravitino.authorization.Privilege;
+
+/**
+ * RangerHiveAuthorizationPlugin is a plugin for Apache Ranger to manage the Hive authorization of
+ * the Apache Gravitino.
+ */
+public class RangerHiveAuthorizationPlugin extends RangerAuthorizationPlugin {
+ public RangerHiveAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super(catalogProvider, config);
+ }
+
+ /**
+ * Ranger hive's privilege have `select`, `update`, `create`, `drop`, `alter`, `index`, `lock`,
+ * `read`, `write`, `repladmin`, `serviceadmin`, `refresh` and `all`. Reference:
+ * ranger/agents-common/src/main/resources/service-defs/ranger-servicedef-hive.json
+ */
+ @Override
+ protected void initMapPrivileges() {
+ mapPrivileges =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
Review Comment:
Before we read or write a table, we should have `use catalog` and `use schema` privilege first.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724283105
##########
integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/RangerContainer.java:
##########
@@ -40,15 +40,18 @@ public class RangerContainer extends BaseContainer {
public static final int RANGER_SERVER_PORT = 6080;
public RangerClient rangerClient;
private String rangerUrl;
- private static final String username = "admin";
- // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
- private static final String password = "rangerR0cks!";
/**
- * for kerberos authentication: authType = "kerberos" username = principal password = path of the
- * keytab file
+ * for kerberos authentication: <br>
+ * authType = "kerberos" <br>
+ * username = principal <br>
+ * password = path of the keytab file <br>
*/
- private static final String authType = "simple";
+ public static final String authType = "simple";
+
+ public static final String rangerUserName = "admin";
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
Review Comment:
This is Apache Ranger original comments, https://github.com/apache/ranger/blob/master/security-admin/scripts/install.properties#L84
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1723290279
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ mapAccesses.put(access.getType(), true);
+ });
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy exists but has different privileges, also return true. Because one Ranger
+ * policy maybe contain multiple Gravitino securable object <br>
+ * 4. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravition securable object's privilege
+ // and roleName
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If exist policy and have same privilege then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(change.getSecurableObject().fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(
+ SecurableObjects.DOT_SPLITTER.splitToList(change.getSecurableObject().fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+ }
+
+ addPolicyItem(policy, change.getRoleName(), change.getSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return true;
+ }
+
+ /**
+ * Remove the securable object's privilege from the policy. <br>
+ * Because Ranger use unique metadata to location Ranger policy and manage the all privileges, So
+ * one Ranger policy maybe contain multiple Gravitino privilege objects. <br>
+ * Remove Ranger policy item condition is: <br>
+ * 1. This Ranger policy item's accesses equal the Gravition securable object's privilege. <br>
Review Comment:
```suggestion
* 1. This Ranger policy item's accesses are equal the Gravitino securable object's privilege. <br>
```
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ mapAccesses.put(access.getType(), true);
+ });
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy exists but has different privileges, also return true. Because one Ranger
+ * policy maybe contain multiple Gravitino securable object <br>
+ * 4. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravition securable object's privilege
+ // and roleName
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If exist policy and have same privilege then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(change.getSecurableObject().fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(
+ SecurableObjects.DOT_SPLITTER.splitToList(change.getSecurableObject().fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+ }
+
+ addPolicyItem(policy, change.getRoleName(), change.getSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return true;
+ }
+
+ /**
+ * Remove the securable object's privilege from the policy. <br>
+ * Because Ranger use unique metadata to location Ranger policy and manage the all privileges, So
+ * one Ranger policy maybe contain multiple Gravitino privilege objects. <br>
+ * Remove Ranger policy item condition is: <br>
+ * 1. This Ranger policy item's accesses equal the Gravition securable object's privilege. <br>
+ * 2. This Ranger policy item's users and groups is empty. <br>
Review Comment:
```suggestion
* 2. This Ranger policy item's users and groups are empty. <br>
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724333323
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy is not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilege -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilege))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role is not exist. */
+ private RangerRole createRangerRole(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role is not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
Review Comment:
@xunliu This seems more readable.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724774456
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
Review Comment:
This is resolved.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#issuecomment-2301237304
Does it support multiple Hive catalog uses one Ranger?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1718402523
##########
api/src/main/java/org/apache/gravitino/authorization/RoleChange.java:
##########
@@ -152,4 +165,88 @@ public String toString() {
return "REMOVESECURABLEOBJECT " + securableObject;
}
}
+
+ /**
+ * A UpdateSecurableObject to update securable object's privilege from role. <br>
+ * The securable object's metadata entity must same as new securable object's metadata entity.
+ * <br>
+ * The securable object's privilege must be different as new securable object's privilege. <br>
+ */
+ final class UpdateSecurableObject implements RoleChange {
+ private final SecurableObject securableObject;
+ private final SecurableObject newSecurableObject;
+
+ private UpdateSecurableObject(
+ SecurableObject securableObject, SecurableObject newSecurableObject) {
+ if (!securableObject.fullName().equals(newSecurableObject.fullName())) {
+ throw new IllegalArgumentException(
+ "The securable object's metadata entity must be same as new securable object's metadata entity.");
+ }
+ if (securableObject.privileges().containsAll(newSecurableObject.privileges())) {
+ throw new IllegalArgumentException(
+ "The securable object's privilege must be different as new securable object's privilege.");
+ }
+
+ this.securableObject = securableObject;
+ this.newSecurableObject = newSecurableObject;
+ }
+
+ /**
+ * Returns the securable object to be updated.
+ *
+ * @return return a securable object.
+ */
+ public SecurableObject getSecurableObject() {
+ return this.securableObject;
+ }
+
+ /**
+ * Returns the new securable object.
+ *
+ * @return return a securable object.
+ */
+ public SecurableObject getNewSecurableObject() {
+ return this.newSecurableObject;
+ }
+
+ /**
+ * Compares this UpdateSecurableObject instance with another object for equality. The comparison
+ * is based on the old securable object and new securable object.
+ *
+ * @param o The object to compare with this instance.
+ * @return true if the given object represents the same add securable object; false otherwise.
Review Comment:
the same as the added securable...
##########
api/src/main/java/org/apache/gravitino/authorization/RoleChange.java:
##########
@@ -152,4 +165,88 @@ public String toString() {
return "REMOVESECURABLEOBJECT " + securableObject;
}
}
+
+ /**
+ * A UpdateSecurableObject to update securable object's privilege from role. <br>
+ * The securable object's metadata entity must same as new securable object's metadata entity.
+ * <br>
+ * The securable object's privilege must be different as new securable object's privilege. <br>
+ */
+ final class UpdateSecurableObject implements RoleChange {
+ private final SecurableObject securableObject;
+ private final SecurableObject newSecurableObject;
+
+ private UpdateSecurableObject(
+ SecurableObject securableObject, SecurableObject newSecurableObject) {
+ if (!securableObject.fullName().equals(newSecurableObject.fullName())) {
+ throw new IllegalArgumentException(
+ "The securable object's metadata entity must be same as new securable object's metadata entity.");
+ }
+ if (securableObject.privileges().containsAll(newSecurableObject.privileges())) {
+ throw new IllegalArgumentException(
+ "The securable object's privilege must be different as new securable object's privilege.");
Review Comment:
According to your code, the error message should be 'The updated securable object's privileges are just a part of that of old one'
##########
authorizations/authorization-ranger/build.gradle.kts:
##########
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+description = "authorization-ranger"
+
+plugins {
+ `maven-publish`
+ id("java")
+ id("idea")
+}
+
+dependencies {
+ implementation(project(":api"))
Review Comment:
it's better to exclude all dependencies from project `api`.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHiveAuthorizationPlugin.java:
##########
@@ -0,0 +1,854 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Privileges;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * RangerHiveAuthorizationPlugin is a plugin for Apache Ranger to manage the Hive authorization of
+ * the Apache Gravitino.
+ */
+public class RangerHiveAuthorizationPlugin extends RangerAuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerHiveAuthorizationPlugin.class);
+
+ public RangerHiveAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
Review Comment:
If we verify the validity, I think it would be better to make it more precise. Take `rangerUrl` for example, I believe the values should NOT be blank.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHiveAuthorizationPlugin.java:
##########
@@ -0,0 +1,854 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Privileges;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * RangerHiveAuthorizationPlugin is a plugin for Apache Ranger to manage the Hive authorization of
+ * the Apache Gravitino.
+ */
+public class RangerHiveAuthorizationPlugin extends RangerAuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerHiveAuthorizationPlugin.class);
+
+ public RangerHiveAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+ }
+
+ /**
+ * Ranger hive's privilege have `select`, `update`, `create`, `drop`, `alter`, `index`, `lock`,
+ * `read`, `write`, `repladmin`, `serviceadmin`, `refresh` and `all`.
+ *
+ * <p>Reference: ranger/agents-common/src/main/resources/service-defs/ranger-servicedef-hive.json
+ */
+ @Override
+ protected void initMapPrivileges() {
+ mapPrivileges =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.MODIFY_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_UPDATE,
+ RangerDefines.ACCESS_TYPE_HIVE_DROP,
+ RangerDefines.ACCESS_TYPE_HIVE_ALTER,
+ RangerDefines.ACCESS_TYPE_HIVE_WRITE))
+ .put(
+ Privilege.Name.SELECT_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_READ, RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .build();
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
Review Comment:
```suggestion
return role.securableObjects().stream().allMatch(securableObject -> {
RangerPolicy policy = findManagedPolicy(securableObject);
return policy != null;
});
```
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHiveAuthorizationPlugin.java:
##########
@@ -0,0 +1,854 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Privileges;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * RangerHiveAuthorizationPlugin is a plugin for Apache Ranger to manage the Hive authorization of
+ * the Apache Gravitino.
+ */
+public class RangerHiveAuthorizationPlugin extends RangerAuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerHiveAuthorizationPlugin.class);
+
+ public RangerHiveAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+ }
+
+ /**
+ * Ranger hive's privilege have `select`, `update`, `create`, `drop`, `alter`, `index`, `lock`,
+ * `read`, `write`, `repladmin`, `serviceadmin`, `refresh` and `all`.
+ *
+ * <p>Reference: ranger/agents-common/src/main/resources/service-defs/ranger-servicedef-hive.json
+ */
+ @Override
+ protected void initMapPrivileges() {
+ mapPrivileges =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.MODIFY_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_UPDATE,
+ RangerDefines.ACCESS_TYPE_HIVE_DROP,
+ RangerDefines.ACCESS_TYPE_HIVE_ALTER,
+ RangerDefines.ACCESS_TYPE_HIVE_WRITE))
+ .put(
+ Privilege.Name.SELECT_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_READ, RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .build();
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ * Reference: https://github.com/apache/gravitino/issues/4509
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
Review Comment:
Can we merge all the changes and update them all in one operation?
##########
api/src/main/java/org/apache/gravitino/authorization/RoleChange.java:
##########
@@ -152,4 +165,88 @@ public String toString() {
return "REMOVESECURABLEOBJECT " + securableObject;
}
}
+
+ /**
+ * A UpdateSecurableObject to update securable object's privilege from role. <br>
Review Comment:
A UpdateSecurableObject is to update securable object's privilege from role
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHiveAuthorizationPlugin.java:
##########
@@ -0,0 +1,854 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Privileges;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * RangerHiveAuthorizationPlugin is a plugin for Apache Ranger to manage the Hive authorization of
+ * the Apache Gravitino.
+ */
+public class RangerHiveAuthorizationPlugin extends RangerAuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerHiveAuthorizationPlugin.class);
+
+ public RangerHiveAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+ }
+
+ /**
+ * Ranger hive's privilege have `select`, `update`, `create`, `drop`, `alter`, `index`, `lock`,
+ * `read`, `write`, `repladmin`, `serviceadmin`, `refresh` and `all`.
+ *
+ * <p>Reference: ranger/agents-common/src/main/resources/service-defs/ranger-servicedef-hive.json
+ */
+ @Override
+ protected void initMapPrivileges() {
+ mapPrivileges =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.MODIFY_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_UPDATE,
+ RangerDefines.ACCESS_TYPE_HIVE_DROP,
+ RangerDefines.ACCESS_TYPE_HIVE_ALTER,
+ RangerDefines.ACCESS_TYPE_HIVE_WRITE))
+ .put(
+ Privilege.Name.SELECT_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_READ, RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .build();
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ * Reference: https://github.com/apache/gravitino/issues/4509
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @VisibleForTesting
+ public List<Privilege> getAllPrivileges() {
+ return mapPrivileges.keySet().stream().map(Privileges::allow).collect(Collectors.toList());
+ }
+
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
Review Comment:
Can we assure that the update process is atomic?
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHiveAuthorizationPlugin.java:
##########
@@ -0,0 +1,854 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Privileges;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * RangerHiveAuthorizationPlugin is a plugin for Apache Ranger to manage the Hive authorization of
+ * the Apache Gravitino.
+ */
+public class RangerHiveAuthorizationPlugin extends RangerAuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerHiveAuthorizationPlugin.class);
+
+ public RangerHiveAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+ }
+
+ /**
+ * Ranger hive's privilege have `select`, `update`, `create`, `drop`, `alter`, `index`, `lock`,
+ * `read`, `write`, `repladmin`, `serviceadmin`, `refresh` and `all`.
+ *
+ * <p>Reference: ranger/agents-common/src/main/resources/service-defs/ranger-servicedef-hive.json
+ */
+ @Override
+ protected void initMapPrivileges() {
+ mapPrivileges =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.MODIFY_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_UPDATE,
+ RangerDefines.ACCESS_TYPE_HIVE_DROP,
+ RangerDefines.ACCESS_TYPE_HIVE_ALTER,
+ RangerDefines.ACCESS_TYPE_HIVE_WRITE))
+ .put(
+ Privilege.Name.SELECT_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_READ, RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .build();
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ * Reference: https://github.com/apache/gravitino/issues/4509
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @VisibleForTesting
+ public List<Privilege> getAllPrivileges() {
+ return mapPrivileges.keySet().stream().map(Privileges::allow).collect(Collectors.toList());
+ }
+
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ List<Privilege> allPrivileges = getAllPrivileges();
+
+ SecurableObject securableObjects =
+ SecurableObjects.parse(metadataObject.fullName(), metadataObject.type(), allPrivileges);
+
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentUserName())
+ .withCreateTime(Instant.now())
+ .build();
+
+ RoleEntity role =
+ RoleEntity.builder()
+ .withId(0L)
+ .withName(OWNER_ROLE_NAME)
+ .withAuditInfo(auditInfo)
+ .withSecurableObjects(Lists.newArrayList(securableObjects))
+ .build();
+
+ Boolean execResult = onRoleCreated(role);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(0L)
+ .withName(preOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ execResult = onRevokedRolesFromUser(Lists.newArrayList(role), userEntity);
+ if (!execResult) {
+ return Boolean.FALSE;
Review Comment:
I believe we should log the failure information regarding the steps that failed.
##########
api/src/main/java/org/apache/gravitino/authorization/RoleChange.java:
##########
@@ -152,4 +165,88 @@ public String toString() {
return "REMOVESECURABLEOBJECT " + securableObject;
}
}
+
+ /**
+ * A UpdateSecurableObject to update securable object's privilege from role. <br>
+ * The securable object's metadata entity must same as new securable object's metadata entity.
Review Comment:
must be the same as...
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHiveAuthorizationPlugin.java:
##########
@@ -0,0 +1,854 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Privileges;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * RangerHiveAuthorizationPlugin is a plugin for Apache Ranger to manage the Hive authorization of
+ * the Apache Gravitino.
+ */
+public class RangerHiveAuthorizationPlugin extends RangerAuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerHiveAuthorizationPlugin.class);
+
+ public RangerHiveAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+ }
+
+ /**
+ * Ranger hive's privilege have `select`, `update`, `create`, `drop`, `alter`, `index`, `lock`,
+ * `read`, `write`, `repladmin`, `serviceadmin`, `refresh` and `all`.
+ *
+ * <p>Reference: ranger/agents-common/src/main/resources/service-defs/ranger-servicedef-hive.json
+ */
+ @Override
+ protected void initMapPrivileges() {
+ mapPrivileges =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.MODIFY_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_UPDATE,
+ RangerDefines.ACCESS_TYPE_HIVE_DROP,
+ RangerDefines.ACCESS_TYPE_HIVE_ALTER,
+ RangerDefines.ACCESS_TYPE_HIVE_WRITE))
+ .put(
+ Privilege.Name.SELECT_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_READ, RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .build();
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ * Reference: https://github.com/apache/gravitino/issues/4509
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @VisibleForTesting
+ public List<Privilege> getAllPrivileges() {
+ return mapPrivileges.keySet().stream().map(Privileges::allow).collect(Collectors.toList());
+ }
+
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ List<Privilege> allPrivileges = getAllPrivileges();
+
+ SecurableObject securableObjects =
+ SecurableObjects.parse(metadataObject.fullName(), metadataObject.type(), allPrivileges);
+
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentUserName())
+ .withCreateTime(Instant.now())
+ .build();
+
+ RoleEntity role =
+ RoleEntity.builder()
+ .withId(0L)
+ .withName(OWNER_ROLE_NAME)
+ .withAuditInfo(auditInfo)
+ .withSecurableObjects(Lists.newArrayList(securableObjects))
+ .build();
+
+ Boolean execResult = onRoleCreated(role);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(0L)
+ .withName(preOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ execResult = onRevokedRolesFromUser(Lists.newArrayList(role), userEntity);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(0L)
+ .withName(preOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ execResult = onRevokedRolesFromGroup(Lists.newArrayList(role), groupEntity);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(0L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ execResult = onGrantedRolesToUser(Lists.newArrayList(role), userEntity);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(0L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ execResult = onGrantedRolesToGroup(Lists.newArrayList(role), groupEntity);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+ }
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ for (Role role : roles) {
+ role.securableObjects()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn("The policy is not exist for the securable object({})", securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject
+ .privileges()
+ .forEach(
+ privilege -> {
+ // Convert Gravitino privilege to Ranger privilege
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .forEach(
+ // Use the Ranger privilege name to search
+ rangerPrivilegeName -> {
+ policy
+ /**
+ * TODO: Maybe we need to add the user to the
+ * Deny/DataMask/RowFilter policy item in the future.
+ */
+ .getPolicyItems()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilegeName))) {
+ // If the user is not exist in the policy item, then
+ // add it.
+ if (!policyItem.getUsers().contains(user.name())) {
+ policyItem.getUsers().add(user.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ AtomicReference<Boolean> result = new AtomicReference<>(Boolean.TRUE);
+ for (Role role : roles) {
+ role.securableObjects()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn("The policy is not exist for the securable object({})", securableObject);
+ result.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject
+ .privileges()
+ .forEach(
+ privilege -> {
+ // Convert Gravitino privilege to Ranger privilege
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .forEach(
+ // Use the Ranger privilege name to search
+ rangerPrivilegeName -> {
+ policy
+ // TODO: Maybe we need to add the user to the
+ // Deny/DataMask/RowFilter policy item in the future.
+ .getPolicyItems()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilegeName))) {
+ // If the user is exist in the policy item, then
+ // remove it.
+ policyItem.getUsers().removeIf(user.name()::equals);
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ if (!result.get()) {
Review Comment:
If the code goes there, the value of `result.get()` can be false, Am I right?
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHiveAuthorizationPlugin.java:
##########
@@ -0,0 +1,854 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Privileges;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.RoleEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * RangerHiveAuthorizationPlugin is a plugin for Apache Ranger to manage the Hive authorization of
+ * the Apache Gravitino.
+ */
+public class RangerHiveAuthorizationPlugin extends RangerAuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerHiveAuthorizationPlugin.class);
+
+ public RangerHiveAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+ }
+
+ /**
+ * Ranger hive's privilege have `select`, `update`, `create`, `drop`, `alter`, `index`, `lock`,
+ * `read`, `write`, `repladmin`, `serviceadmin`, `refresh` and `all`.
+ *
+ * <p>Reference: ranger/agents-common/src/main/resources/service-defs/ranger-servicedef-hive.json
+ */
+ @Override
+ protected void initMapPrivileges() {
+ mapPrivileges =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.MODIFY_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_UPDATE,
+ RangerDefines.ACCESS_TYPE_HIVE_DROP,
+ RangerDefines.ACCESS_TYPE_HIVE_ALTER,
+ RangerDefines.ACCESS_TYPE_HIVE_WRITE))
+ .put(
+ Privilege.Name.SELECT_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_READ, RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .build();
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ * Reference: https://github.com/apache/gravitino/issues/4509
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @VisibleForTesting
+ public List<Privilege> getAllPrivileges() {
+ return mapPrivileges.keySet().stream().map(Privileges::allow).collect(Collectors.toList());
+ }
+
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ List<Privilege> allPrivileges = getAllPrivileges();
+
+ SecurableObject securableObjects =
+ SecurableObjects.parse(metadataObject.fullName(), metadataObject.type(), allPrivileges);
+
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentUserName())
+ .withCreateTime(Instant.now())
+ .build();
+
+ RoleEntity role =
+ RoleEntity.builder()
+ .withId(0L)
+ .withName(OWNER_ROLE_NAME)
+ .withAuditInfo(auditInfo)
+ .withSecurableObjects(Lists.newArrayList(securableObjects))
+ .build();
+
+ Boolean execResult = onRoleCreated(role);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(0L)
+ .withName(preOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ execResult = onRevokedRolesFromUser(Lists.newArrayList(role), userEntity);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(0L)
+ .withName(preOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ execResult = onRevokedRolesFromGroup(Lists.newArrayList(role), groupEntity);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(0L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ execResult = onGrantedRolesToUser(Lists.newArrayList(role), userEntity);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(0L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ execResult = onGrantedRolesToGroup(Lists.newArrayList(role), groupEntity);
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+ }
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ for (Role role : roles) {
+ role.securableObjects()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn("The policy is not exist for the securable object({})", securableObject);
Review Comment:
is -> does
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1723129415
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
Review Comment:
I think we should add these to the comments. Maybe we should extract a class for precise filter.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#issuecomment-2297824047
Do you have e2e tests for this pull request?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1722651057
##########
authorizations/authorization-ranger/src/main/resources/META-INF/services/org.apache.gravitino.authorization.ranger.RangerAuthorization:
##########
@@ -0,0 +1,19 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+org.apache.gravitino.authorization.ranger.RangerAuthorization
Review Comment:
OK, I fixed this problem
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "lw-yang (via GitHub)" <gi...@apache.org>.
lw-yang commented on PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#issuecomment-2298038013
LGTM
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1722755250
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
Review Comment:
Will this client fail to grant role?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1722760002
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
Review Comment:
Maybe privilegesMapping is better?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1722761202
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
Review Comment:
What's the meaning of precise filter?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724216553
##########
integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/RangerContainer.java:
##########
@@ -40,15 +40,18 @@ public class RangerContainer extends BaseContainer {
public static final int RANGER_SERVER_PORT = 6080;
public RangerClient rangerClient;
private String rangerUrl;
- private static final String username = "admin";
- // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
- private static final String password = "rangerR0cks!";
/**
- * for kerberos authentication: authType = "kerberos" username = principal password = path of the
- * keytab file
+ * for kerberos authentication: <br>
+ * authType = "kerberos" <br>
+ * username = principal <br>
+ * password = path of the keytab file <br>
*/
- private static final String authType = "simple";
+ public static final String authType = "simple";
+
+ public static final String rangerUserName = "admin";
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
Review Comment:
```suggestion
// Apache Ranger Password should have the character size bigger than 8 with at least one alphabet and one numeric.
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1719255002
##########
integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/RangerContainer.java:
##########
@@ -40,15 +40,18 @@ public class RangerContainer extends BaseContainer {
public static final int RANGER_SERVER_PORT = 6080;
public RangerClient rangerClient;
private String rangerUrl;
- private static final String username = "admin";
- // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
- private static final String password = "rangerR0cks!";
/**
- * for kerberos authentication: authType = "kerberos" username = principal password = path of the
- * keytab file
+ * for kerberos authentication: <br>
+ * authType = "kerberos" <br>
+ * username = principal <br>
+ * password = path of the keytab file <br>
*/
- private static final String authType = "simple";
+ public static final String authType = "simple";
+
+ public static final String rangerUserName = "admin";
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ public static final String rangerPassword = "rangerR0cks!";
Review Comment:
R0 -> Ro
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
Review Comment:
So in what case will these methods `doAddSecurableObject`, `doRemoveSecurableObject`, and `doUpdateSecurableObject` will false, can you add some comments on the corresponding methods?
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
Review Comment:
I still recommend that we merge the changes first and then to the actions.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy is not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilege -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilege))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role is not exist. */
Review Comment:
does not exists, so does in line 635.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
Review Comment:
Please simplify the method as I suggested before.
##########
api/src/main/java/org/apache/gravitino/authorization/RoleChange.java:
##########
@@ -152,4 +165,88 @@ public String toString() {
return "REMOVESECURABLEOBJECT " + securableObject;
}
}
+
+ /**
+ * A UpdateSecurableObject to update securable object's privilege from role. <br>
+ * The securable object's metadata entity must same as new securable object's metadata entity.
+ * <br>
+ * The securable object's privilege must be different as new securable object's privilege. <br>
+ */
+ final class UpdateSecurableObject implements RoleChange {
+ private final SecurableObject securableObject;
+ private final SecurableObject newSecurableObject;
+
+ private UpdateSecurableObject(
+ SecurableObject securableObject, SecurableObject newSecurableObject) {
+ if (!securableObject.fullName().equals(newSecurableObject.fullName())) {
+ throw new IllegalArgumentException(
+ "The securable object's metadata entity must be same as new securable object's metadata entity.");
+ }
+ if (securableObject.privileges().containsAll(newSecurableObject.privileges())) {
+ throw new IllegalArgumentException(
+ "The securable object's privilege must be different as new securable object's privilege.");
Review Comment:
This has not been resolved.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy is not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilege -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilege))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role is not exist. */
+ private RangerRole createRangerRole(String roleName) {
Review Comment:
Suggest rename it as `createRangerRoleIfNotExists`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1721304932
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1023 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
Review Comment:
```java
return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
```
##########
api/src/main/java/org/apache/gravitino/authorization/RoleChange.java:
##########
@@ -149,7 +189,101 @@ public int hashCode() {
*/
@Override
public String toString() {
- return "REMOVESECURABLEOBJECT " + securableObject;
+ return "REMOVESECURABLEOBJECT " + roleName + " " + securableObject;
+ }
+ }
+
+ /**
+ * A UpdateSecurableObject is to update securable object's privilege from role. <br>
+ * The securable object's metadata entity must be the same as new securable object's metadata
+ * entity. <br>
+ * The securable object's privilege must be different as new securable object's privilege. <br>
+ */
+ final class UpdateSecurableObject implements RoleChange {
+ private final String roleName;
+ private final SecurableObject securableObject;
+ private final SecurableObject newSecurableObject;
+
+ private UpdateSecurableObject(
+ String roleName, SecurableObject securableObject, SecurableObject newSecurableObject) {
+ if (!securableObject.fullName().equals(newSecurableObject.fullName())) {
+ throw new IllegalArgumentException(
+ "The securable object's metadata entity must be same as new securable object's metadata entity.");
+ }
+ if (securableObject.privileges().containsAll(newSecurableObject.privileges())) {
+ throw new IllegalArgumentException(
+ "The updated securable object's privilege must be different as new securable object's privilege.");
Review Comment:
This place has not been resolved.
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1023 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy is not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilege -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilege))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
Review Comment:
is not exists
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#issuecomment-2296375571
If we set a schema the privilege `read table`, will it present schema.* in the Ranger?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1721845748
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1015 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+
+ role.securableObjects().stream()
Review Comment:
I know what you mean.
The First step is to add a user to this role. But we also need to check and add this role to the policy.
otherwise, the role may not be associated with policy item.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1721943510
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1015 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+
+ role.securableObjects().stream()
Review Comment:
You are right.
I modified these code.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1721648253
##########
api/src/main/java/org/apache/gravitino/authorization/RoleChange.java:
##########
@@ -149,7 +189,101 @@ public int hashCode() {
*/
@Override
public String toString() {
- return "REMOVESECURABLEOBJECT " + securableObject;
+ return "REMOVESECURABLEOBJECT " + roleName + " " + securableObject;
+ }
+ }
+
+ /**
+ * A UpdateSecurableObject is to update securable object's privilege from role. <br>
+ * The securable object's metadata entity must be the same as new securable object's metadata
+ * entity. <br>
+ * The securable object's privilege must be different as new securable object's privilege. <br>
+ */
+ final class UpdateSecurableObject implements RoleChange {
+ private final String roleName;
+ private final SecurableObject securableObject;
+ private final SecurableObject newSecurableObject;
+
+ private UpdateSecurableObject(
+ String roleName, SecurableObject securableObject, SecurableObject newSecurableObject) {
+ if (!securableObject.fullName().equals(newSecurableObject.fullName())) {
+ throw new IllegalArgumentException(
+ "The securable object's metadata entity must be same as new securable object's metadata entity.");
+ }
+ if (securableObject.privileges().containsAll(newSecurableObject.privileges())) {
Review Comment:
Why do we need this limit?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724516409
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,998 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have a Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
Review Comment:
Could you extract a method to PolicyUtil class or PolicyHelper class?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724512836
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,998 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have a Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
Review Comment:
```suggestion
* Because a Ranger policy maybe contains multiple securable objects, so we didn't directly
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724790047
##########
authorizations/authorization-ranger/src/test/java/org/apache/gravitino/authorization/ranger/integration/test/RangerITEnv.java:
##########
@@ -311,4 +314,11 @@ protected static void cleanAllPolicy(String serviceName) {
throw new RuntimeException(e);
}
}
+
+ /**
+ * Didn't call this function in the Lambda function body, It will return a random function name
Review Comment:
Don't or Do not
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,583 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.authorization.ranger.reference.VXGroup;
+import org.apache.gravitino.authorization.ranger.reference.VXGroupList;
+import org.apache.gravitino.authorization.ranger.reference.VXUser;
+import org.apache.gravitino.authorization.ranger.reference.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Ranger authorization operations plugin abstract class. <br>
+ * 1. For Ranger limit, The same metadata object only has a unique Ranger policy, So a Ranger policy
+ * maybe contains multiple Gravitino securable objects. <br>
+ * 2. For easy management, each Ranger privilege will create one RangerPolicyItemAccess in the
+ * policy. <br>
+ * 3. Ranger also have Role concept, and support adds multiple users or groups in the Ranger Role,
+ * So we can use the Ranger Role to implement the Gravitino Role. <br>
+ * 4. The Ranger policy also supports multiple users and groups, But we only use a user or group to
+ * implement Gravitino Owner concept. <br>
+ */
+public class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected String rangerServiceName;
+ protected RangerClientExtend rangerClient;
+ private RangerHelper rangerHelper;
+ @VisibleForTesting public final String rangerAdminName;
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ rangerAdminName = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ RangerHelper.check(rangerUrl != null, "Ranger admin URL is required");
+ RangerHelper.check(authType != null, "Ranger auth type is required");
+ RangerHelper.check(rangerAdminName != null, "Ranger username is required");
+ RangerHelper.check(password != null, "Ranger password is required");
+ RangerHelper.check(rangerServiceName != null, "Ranger service name is required");
+ rangerClient = new RangerClientExtend(rangerUrl, authType, rangerAdminName, password);
+ rangerHelper = new RangerHelper(this, catalogProvider);
+ }
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return rangerHelper.privilegesMapping.get(name);
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(rangerHelper.ownerPrivileges);
+ }
+
+ /**
+ * Create a new role in the Ranger. <br>
+ * 1. Create a policy for metadata object. <br>
+ * 2. Save role name in the Policy items. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ return rangerHelper.checkRangerRole(role.name());
+ }
+
+ /** Remove the role name from the Ranger policy item, and delete this Role in the Ranger. <br> */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, delete the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), rangerAdminName, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult = doRemoveSecurableObject((RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult = doUpdateSecurableObject((RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ * 1. If the metadata object already has an owner, then transfer the ownership from preOwner to
+ * newOwner, The function params preOwner and newOwner don't equal null. <br>
+ * 2. If the metadata object doesn't have an owner, then set the owner to newOwner, The function
+ * params preOwner equal null and newOwner don't equal null. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object.
+ * @param newOwner The new owner of the metadata object.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ RangerHelper.check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = rangerHelper.findManagedPolicy(metadataObject);
+ try {
+ if (policy == null) {
+ policy = rangerHelper.addOwnerToNewPolicy(metadataObject, newOwner);
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerHelper.updatePolicyOwner(policy, preOwner, newOwner);
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this user to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param user The user to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role: {} to user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this user from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param user The user to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
Review Comment:
As you have ignored the result of `checkRangerRole`, how can you assure that the role exists?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724993429
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,556 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.reference.VXGroup;
+import org.apache.gravitino.authorization.ranger.reference.VXGroupList;
+import org.apache.gravitino.authorization.ranger.reference.VXUser;
+import org.apache.gravitino.authorization.ranger.reference.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Ranger authorization operations plugin abstract class. <br>
+ * 1. For Ranger limit, The same metadata object only has a unique Ranger policy, So a Ranger policy
+ * maybe contains multiple Gravitino securable objects. <br>
+ * 2. For easy management, each Ranger privilege will create one RangerPolicyItemAccess in the
+ * policy. <br>
+ * 3. Ranger also have Role concept, and support adds multiple users or groups in the Ranger Role,
+ * So we can use the Ranger Role to implement the Gravitino Role. <br>
+ * 4. The Ranger policy also supports multiple users and groups, But we only use a user or group to
+ * implement Gravitino Owner concept. <br>
+ */
+public class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected String rangerServiceName;
+ protected RangerClientExtend rangerClient;
+ private RangerHelper rangerHelper;
+ @VisibleForTesting public final String rangerAdminName;
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ rangerAdminName = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ RangerHelper.check(rangerUrl != null, "Ranger admin URL is required");
+ RangerHelper.check(authType != null, "Ranger auth type is required");
+ RangerHelper.check(rangerAdminName != null, "Ranger username is required");
+ RangerHelper.check(password != null, "Ranger password is required");
+ RangerHelper.check(rangerServiceName != null, "Ranger service name is required");
+ rangerClient = new RangerClientExtend(rangerUrl, authType, rangerAdminName, password);
+ rangerHelper = new RangerHelper(this, catalogProvider);
+ }
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return rangerHelper.privilegesMapping.get(name);
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(rangerHelper.ownerPrivileges);
+ }
+
+ /**
+ * Create a new role in the Ranger. <br>
+ * 1. Create a policy for metadata object. <br>
+ * 2. Save role name in the Policy items. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ return rangerHelper.checkRangerRole(role.name());
+ }
+
+ /** Remove the role name from the Ranger policy item, and delete this Role in the Ranger. <br> */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, delete the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), rangerAdminName, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult = doRemoveSecurableObject((RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult = doUpdateSecurableObject((RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ * 1. If the metadata object already has an owner, then transfer the ownership from preOwner to
+ * newOwner, The function params preOwner and newOwner don't equal null. <br>
+ * 2. If the metadata object doesn't have an owner, then set the owner to newOwner, The function
+ * params preOwner equal null and newOwner don't equal null. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object.
+ * @param newOwner The new owner of the metadata object.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ RangerHelper.check(newOwner != null, "The newOwner must be not null");
+
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+
+ RangerPolicy policy = rangerHelper.findManagedPolicy(metadataObject);
+ try {
+ if (policy == null) {
+ policy = rangerHelper.addOwnerToNewPolicy(metadataObject, newOwner);
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerHelper.updatePolicyOwner(policy, preOwner, newOwner);
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this user to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param user The user to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role: {} to user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this user from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param user The user to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this group to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Grant role: {} to group: {} failed!", role, group, e);
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this group from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param group The group to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Revoke role: {} from group: {} failed!", role, group, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) already exists in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) doesn't exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) doesn't exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) doesn't exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) doesn't exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Add the securable object's privilege to the Ranger policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = rangerHelper.findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravitino securable object's privilege
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If it exists policy with the same privilege, then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = rangerHelper.createPolicyAddResources(change.getSecurableObject());
+ }
+
+ rangerHelper.addPolicyItem(policy, change.getRoleName(), change.getSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return true;
+ }
+
+ /**
+ * Remove the securable object's privilege from the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, then remove role name in the policy items.
+ * <br>
+ * 3. If policy does not contain any policy item, then delete this policy. <br>
+ */
+ private boolean doRemoveSecurableObject(RoleChange.RemoveSecurableObject change) {
+ RangerPolicy policy = rangerHelper.findManagedPolicy(change.getSecurableObject());
+ if (policy == null) {
+ LOG.warn(
+ "Cannot find the Ranger policy({}) for the Gravitino securable object({})!",
+ change.getRoleName(),
+ change.getSecurableObject().fullName());
+ // Don't throw exception or return false, because need support immutable operation.
+ return true;
+ }
+
+ policy
+ .getPolicyItems()
+ .forEach(
+ policyItem -> {
+ boolean match =
+ policyItem.getAccesses().stream()
+ .allMatch(
+ // Find the policy item that matches access and role
+ access -> {
+ // Use Gravitino privilege to search the Ranger policy item's access
+ boolean matchPrivilege =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(
+ privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .anyMatch(privilege -> privilege.equals(access.getType()));
+ return matchPrivilege;
+ });
+ if (match) {
+ policyItem.getRoles().removeIf(change.getRoleName()::equals);
+ }
+ });
+
+ // If the policy does have any role and user and group, then remove it.
+ policy
+ .getPolicyItems()
+ .removeIf(
+ policyItem ->
+ policyItem.getRoles().isEmpty()
+ && policyItem.getUsers().isEmpty()
+ && policyItem.getGroups().isEmpty());
+
+ try {
+ if (policy.getPolicyItems().size() == 0) {
+ rangerClient.deletePolicy(policy.getId());
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ LOG.error("Failed to remove the policy item from the Ranger policy {}!", policy);
+ throw new RuntimeException(e);
+ }
+ return true;
+ }
+
+ /**
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists, then user new securable object's privilege to update. <br>
+ * 3. If the policy does not exist, return false. <br>
+ */
+ private boolean doUpdateSecurableObject(RoleChange.UpdateSecurableObject change) {
+ RangerPolicy policy = rangerHelper.findManagedPolicy(change.getSecurableObject());
+ if (policy == null) {
+ LOG.warn(
+ "Cannot find the Ranger policy({}) for the Gravitino securable object({})!",
+ change.getRoleName(),
+ change.getSecurableObject().fullName());
+ // Don't throw exception or return false, because need support immutable operation.
+ return false;
+ }
+
+ rangerHelper.removePolicyItem(policy, change.getRoleName(), change.getSecurableObject());
+ rangerHelper.addPolicyItem(policy, change.getRoleName(), change.getNewSecurableObject());
+ try {
+ if (policy.getId() == null) {
Review Comment:
So in what case will the id be null?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724987141
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerHelper.java:
##########
@@ -0,0 +1,539 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.commons.lang.StringUtils;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This class is a helper class for the Ranger authorization plugin. It provides the ability to
+ * manage the Ranger policies and roles.
+ */
+public class RangerHelper {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerHelper.class);
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+ RangerAuthorizationPlugin rangerAuthorizationPlugin;
+
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ /** The owner privileges, the owner can do anything on the metadata object */
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise search, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, If you use `db.table` condition to search policy, the Ranger will
+ * match `db1.table1`, `db1.table2`, `db*.table*`, So we need to manually precisely filter this
+ * research results. <br>
+ * policySearchKeys: The search Ranger policy condition key defines. <br>
+ * policyPreciseFilterKeys: The precise filter Ranger search results key defines <br>
+ */
+ protected List<String> policySearchKeys = null;
+
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public RangerHelper(RangerAuthorizationPlugin rangerAuthorizationPlugin, String catalogProvider) {
+ this.rangerAuthorizationPlugin = rangerAuthorizationPlugin;
+ switch (catalogProvider) {
+ case "hive":
+ initPrivilegesMapping();
+ initOwnerPrivileges();
+ initPolicySearchKeys();
+ initPreciseFilterKeys();
+ break;
+ default:
+ throw new IllegalArgumentException(
+ "Authorization plugin unsupported catalog provider: " + catalogProvider);
+ }
+ }
+
+ /** Initial mapping Gravitino privilege name to the underlying authorization system privileges. */
+ private void initPrivilegesMapping() {
+ privilegesMapping =
+ ImmutableMap.<Privilege.Name, Set<String>>builder()
+ .put(
+ Privilege.Name.CREATE_SCHEMA,
+ ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.CREATE_TABLE, ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_CREATE))
+ .put(
+ Privilege.Name.MODIFY_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_UPDATE,
+ RangerDefines.ACCESS_TYPE_HIVE_ALTER,
+ RangerDefines.ACCESS_TYPE_HIVE_WRITE))
+ .put(
+ Privilege.Name.SELECT_TABLE,
+ ImmutableSet.of(
+ RangerDefines.ACCESS_TYPE_HIVE_READ, RangerDefines.ACCESS_TYPE_HIVE_SELECT))
+ .build();
+ }
+
+ /** Initial Owner privileges */
+ private void initOwnerPrivileges() {
+ ownerPrivileges = ImmutableSet.of(RangerDefines.ACCESS_TYPE_HIVE_ALL);
+ }
+
+ /** Initial Ranger policy search key defines */
+ private void initPolicySearchKeys() {
+ policySearchKeys =
+ Arrays.asList(
+ RangerDefines.SEARCH_FILTER_DATABASE,
+ RangerDefines.SEARCH_FILTER_TABLE,
+ RangerDefines.SEARCH_FILTER_COLUMN);
+ }
+
+ /** Initial precise filter key defines */
+ private void initPreciseFilterKeys() {
+ policyPreciseFilterKeys =
+ Arrays.asList(
+ RangerDefines.RESOURCE_DATABASE,
+ RangerDefines.RESOURCE_TABLE,
+ RangerDefines.RESOURCE_COLUMN);
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Set<String> setAccesses = new HashSet<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (setAccesses.contains(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ setAccesses.add(access.getType());
+ });
+ }
+
+ /**
+ * Add policy item access items base the securable object's privileges. <br>
+ * We cannot clean the policy items because one Ranger policy maybe contains multiple Gravitino
+ * securable objects. <br>
+ */
+ void addPolicyItem(RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkPrivileges(securableObject);
+
+ // Add the policy items by the securable object's privileges
+ securableObject
+ .privileges()
+ .forEach(
+ gravitinoPrivilege -> {
+ // Translate the Gravitino privilege to map Ranger privilege
+ rangerAuthorizationPlugin
+ .translatePrivilege(gravitinoPrivilege.name())
+ .forEach(
+ mappedPrivilege -> {
+ // Find the policy item that matches Gravitino privilege
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItems =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ access -> access.getType().equals(mappedPrivilege));
+ })
+ .collect(Collectors.toList());
+
+ if (matchPolicyItems.size() == 0) {
+ // If the policy item does not exist, then create a new policy item
+ RangerPolicy.RangerPolicyItem policyItem =
+ new RangerPolicy.RangerPolicyItem();
+ RangerPolicy.RangerPolicyItemAccess access =
+ new RangerPolicy.RangerPolicyItemAccess();
+ access.setType(mappedPrivilege);
+ policyItem.getAccesses().add(access);
+ policyItem.getRoles().add(roleName);
+ if (Privilege.Condition.ALLOW == gravitinoPrivilege.condition()) {
+ policy.getPolicyItems().add(policyItem);
+ } else {
+ policy.getDenyPolicyItems().add(policyItem);
+ }
+ } else {
+ // If the policy item exists, then add the role to the policy item
+ matchPolicyItems.stream()
+ .forEach(
+ policyItem -> {
+ // If the role is not in the policy item, then add it
+ if (!policyItem.getRoles().contains(roleName)) {
+ policyItem.getRoles().add(roleName);
+ }
+ });
+ }
+ });
+ });
+ }
+
+ /**
+ * Remove policy item base the securable object's privileges and role name. <br>
+ * We cannot directly clean the policy items because one Ranger policy maybe contains multiple
+ * Gravitino privilege objects. <br>
+ */
+ void removePolicyItem(RangerPolicy policy, String roleName, SecurableObject securableObject) {
+ // First check the privilege if support in the Ranger Hive
+ checkPrivileges(securableObject);
+
+ // Delete the policy role base the securable object's privileges
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ boolean matchPrivilege =
+ securableObject.privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(
+ privilege ->
+ rangerAuthorizationPlugin
+ .translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .anyMatch(
+ privilege -> {
+ return access.getType().equals(privilege);
+ });
+ if (matchPrivilege
+ && !policyItem.getUsers().isEmpty()
+ && !policyItem.getGroups().isEmpty()) {
+ // We can only remove this policy item if there are no users or groups
+ policyItem.getRoles().removeIf(roleName::equals);
+ }
+ });
+ });
+
+ // Delete the policy items if the roles are empty and not ownership policy item
+ policy
+ .getPolicyItems()
+ .removeIf(
+ policyItem -> {
+ return policyItem.getRoles().isEmpty()
+ && policyItem.getUsers().isEmpty()
+ && policyItem.getGroups().isEmpty();
+ });
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param securableObject The securable object to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ private boolean checkPrivileges(SecurableObject securableObject) {
+ securableObject
+ .privileges()
+ .forEach(
+ privilege -> {
+ check(
+ privilegesMapping.containsKey(privilege.name()),
+ "This privilege %s is not supported in the Ranger hive authorization",
+ privilege.name());
+ });
+ return true;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> searchFilters = new HashMap<>();
+ Map<String, String> preciseFilters = new HashMap<>();
+ searchFilters.put(
+ RangerDefines.SEARCH_FILTER_SERVICE_NAME, rangerAuthorizationPlugin.rangerServiceName);
+ searchFilters.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ searchFilters.put(policySearchKeys.get(i), nsMetadataObj.get(i));
+ preciseFilters.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies =
+ rangerAuthorizationPlugin.rangerClient.findPolicies(searchFilters);
+
+ if (!policies.isEmpty()) {
+ /**
+ * Because Ranger doesn't support the precise search, Ranger will return the policy meets
+ * the wildcard(*,?) conditions, If you use `db.table` condition to search policy, the
+ * Ranger will match `db1.table1`, `db1.table2`, `db*.table*`, So we need to manually
+ * precisely filter this research results.
+ */
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilters.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilters.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are managed by Gravitino.
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ if (policies.isEmpty()) {
+ return null;
+ }
+ RangerPolicy policy = policies.get(0);
+ // Delegating Gravitino management policies cannot contain duplicate privilege
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ protected boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ RangerRole role =
+ rangerAuthorizationPlugin.rangerClient.getRole(
+ roleName,
+ rangerAuthorizationPlugin.rangerAdminName,
+ rangerAuthorizationPlugin.rangerServiceName);
+ if (role == null) {
+ return false;
+ }
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ protected GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users =
+ StringUtils.isEmpty(userName) ? Sets.newHashSet() : Sets.newHashSet(userName);
+ Set<String> groups =
+ StringUtils.isEmpty(groupName) ? Sets.newHashSet() : Sets.newHashSet(groupName);
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(rangerAuthorizationPlugin.rangerAdminName);
+ roleRequest.setTargetRoles(Sets.newHashSet(roleName));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ protected RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole =
+ rangerAuthorizationPlugin.rangerClient.getRole(
+ roleName,
+ rangerAuthorizationPlugin.rangerAdminName,
+ rangerAuthorizationPlugin.rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ LOG.warn("The role({}) is not exist in the Ranger!", roleName);
Review Comment:
```suggestion
LOG.warn("The role({}) doesn't exist in the Ranger!", roleName);
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724338147
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1006 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExtend rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> privilegesMapping = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manually precisely filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExtend(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return privilegesMapping.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return privilegesMapping.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have a Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ try {
+ return role.securableObjects().stream().allMatch(object -> findManagedPolicy(object) != null);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * an owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already has an
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ // Find matching policy items based on the owner's privileges
+ List<RangerPolicy.RangerPolicyItem> matchPolicyItmes =
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .collect(Collectors.toList());
+ // Add or remove the owner in the policy item
+ matchPolicyItmes.forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ if (!policyItem.getUsers().contains(newOwner.name())) {
+ policyItem.getUsers().add(newOwner.name());
+ }
+ } else {
+ if (!policyItem.getGroups().contains(newOwner.name())) {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ }
+ });
+ // If the policy item is not equal to owner's privileges, then update the policy
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .filter(
+ ownerPrivilege -> {
+ return matchPolicyItmes.stream()
+ .noneMatch(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess -> {
+ return ownerPrivilege.equals(policyItemAccess.getType());
+ });
+ });
+ })
+ .forEach(
+ // Add lose owner's privilege to the policy
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ // Each owner's privilege will create one RangerPolicyItemAccess in the policy
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role to user failed!", e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contains multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ onUserAdded(user);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group does not exist, then create it.
+ onGroupAdded(group);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ onGroupAdded(group);
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exists in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role does not exist. */
+ private RangerRole createRangerRoleIfNotExists(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role does not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manually precisely filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are managed by Gravitino.
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ }
+
+ /**
+ * For easy management, each privilege will create one RangerPolicyItemAccess in the policy.
+ *
+ * @param policyItem The policy item to check
+ * @throws AuthorizationPluginException If the policy item contains more than one access type
+ */
+ void checkPolicyItemAccess(RangerPolicy.RangerPolicyItem policyItem)
+ throws AuthorizationPluginException {
+ if (policyItem.getAccesses().size() != 1) {
+ throw new AuthorizationPluginException(
+ "The access type only have one in the delegate Gravitino management policy");
+ }
+ Map<String, Boolean> mapAccesses = new HashMap<>();
+ policyItem
+ .getAccesses()
+ .forEach(
+ access -> {
+ if (mapAccesses.containsKey(access.getType()) && mapAccesses.get(access.getType())) {
+ throw new AuthorizationPluginException(
+ "Contain duplicate privilege(%s) in the delegate Gravitino management policy ",
+ access.getType());
+ }
+ mapAccesses.put(access.getType(), true);
+ });
+ }
+
+ /**
+ * Add the securable object's privilege to the policy. <br>
+ * 1. Find the policy base the metadata object. <br>
+ * 2. If the policy exists and has the same privilege, because support idempotent operation, so
+ * return true. <br>
+ * 3. If the policy exists but has different privileges, also return true. Because one Ranger
+ * policy maybe contain multiple Gravitino securable object <br>
+ * 4. If the policy does not exist, then create a new policy. <br>
+ */
+ private boolean doAddSecurableObject(RoleChange.AddSecurableObject change) {
+ RangerPolicy policy = findManagedPolicy(change.getSecurableObject());
+
+ if (policy != null) {
+ // Check the policy item's accesses and roles equal the Gravitino securable object's privilege
+ // and roleName
+ Set<String> policyPrivileges =
+ policy.getPolicyItems().stream()
+ .filter(policyItem -> policyItem.getRoles().contains(change.getRoleName()))
+ .flatMap(policyItem -> policyItem.getAccesses().stream())
+ .map(RangerPolicy.RangerPolicyItemAccess::getType)
+ .collect(Collectors.toSet());
+ Set<String> newPrivileges =
+ change.getSecurableObject().privileges().stream()
+ .filter(Objects::nonNull)
+ .flatMap(privilege -> translatePrivilege(privilege.name()).stream())
+ .filter(Objects::nonNull)
+ .collect(Collectors.toSet());
+ if (policyPrivileges.containsAll(newPrivileges)) {
+ LOG.info(
+ "The privilege({}) already added to Ranger policy({})!",
+ policy.getName(),
+ change.getSecurableObject().fullName());
+ // If it exists policy with the same privilege, then directly return true, because support
+ // idempotent operation.
+ return true;
+ }
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(change.getSecurableObject().fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(
+ SecurableObjects.DOT_SPLITTER.splitToList(change.getSecurableObject().fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ List<String> rangerDefinesList =
+ Lists.newArrayList(
+ RangerDefines.RESOURCE_DATABASE,
+ RangerDefines.RESOURCE_TABLE,
+ RangerDefines.RESOURCE_COLUMN);
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy.getResources().put(rangerDefinesList.get(i), policyResource);
+ }
+ }
+
+ addPolicyItem(policy, change.getRoleName(), change.getSecurableObject());
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return true;
+ }
+
+ /**
+ * Remove the securable object's privilege from the policy. <br>
+ * Because Ranger uses unique metadata to location Ranger policy and manages all the privileges,
+ * So A Ranger policy maybe contains multiple Gravitino privilege objects. <br>
+ * Remove Ranger policy item condition is: <br>
+ * 1. This Ranger policy item's accesses are equal the Gravitino securable object's privilege.
+ * <br>
+ * 2. This Ranger policy item's users and groups are empty. <br>
+ * If policy didn't have any policy item, then delete this policy: <br>
+ */
+ private boolean doRemoveSecurableObject(
Review Comment:
Could we reuse `removePolicyItem`?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "jerqi (via GitHub)" <gi...@apache.org>.
jerqi commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724343686
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,1027 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import com.google.errorprone.annotations.FormatMethod;
+import com.google.errorprone.annotations.FormatString;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.defines.VXGroup;
+import org.apache.gravitino.authorization.ranger.defines.VXGroupList;
+import org.apache.gravitino.authorization.ranger.defines.VXUser;
+import org.apache.gravitino.authorization.ranger.defines.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.exceptions.AuthorizationPluginException;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.model.RangerRole;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.apache.ranger.plugin.util.SearchFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Ranger authorization operations plugin abstract class. */
+public abstract class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected RangerClientExt rangerClient;
+ protected String rangerServiceName;
+ /** Mapping Gravitino privilege name to the underlying authorization system privileges. */
+ protected Map<Privilege.Name, Set<String>> mapPrivileges = null;
+ // The owner privileges, the owner can do anything on the metadata object
+ protected Set<String> ownerPrivileges = null;
+
+ /**
+ * Because Ranger doesn't support the precise filter, Ranger will return the policy meets the
+ * wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1` So we need
+ * to manual precise filter the policies.
+ */
+ // Search Ranger policy filter keys
+ protected List<String> policyFilterKeys = null;
+ // Search Ranger policy precise filter keys
+ protected List<String> policyPreciseFilterKeys = null;
+
+ public static final String MANAGED_BY_GRAVITINO = "MANAGED_BY_GRAVITINO";
+
+ // TODO: Maybe need to move to the configuration in the future
+ public static final String RANGER_ADMIN_NAME = "admin";
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ String username = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ check(rangerUrl != null, "Ranger admin URL is required");
+ check(authType != null, "Ranger auth type is required");
+ check(username != null, "Ranger username is required");
+ check(password != null, "Ranger password is required");
+ check(rangerServiceName != null, "Ranger service name is required");
+
+ rangerClient = new RangerClientExt(rangerUrl, authType, username, password);
+
+ initMapPrivileges();
+ initOwnerPrivileges();
+ initPolicyFilterKeys();
+ initPreciseFilterKeys();
+ }
+
+ /**
+ * Different underlying permission system may have different privilege names, this function is
+ * used to initialize the privilege mapping.
+ */
+ protected abstract void initMapPrivileges();
+
+ /**
+ * Different underlying permission system may have different owner privilege names, this function
+ * is used to initialize the owner privilege mapping.
+ */
+ protected abstract void initOwnerPrivileges();
+
+ // Initial Ranger policy filter keys
+ protected abstract void initPolicyFilterKeys();
+ // Initial Ranger policy precise filter keys
+ protected abstract void initPreciseFilterKeys();
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return mapPrivileges.get(name);
+ }
+
+ /**
+ * Whether this privilege is underlying permission system supported
+ *
+ * @param name The privilege name to check
+ * @return true if the privilege is supported, otherwise false
+ */
+ protected boolean checkPrivilege(Privilege.Name name) {
+ return mapPrivileges.containsKey(name);
+ }
+
+ @FormatMethod
+ protected void check(boolean condition, @FormatString String message, Object... args) {
+ if (!condition) {
+ throw new AuthorizationPluginException(message, args);
+ }
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(ownerPrivileges);
+ }
+
+ /**
+ * Because Ranger does not have Role concept, Each metadata object will have a unique Ranger
+ * policy. we can use one or more Ranger policy to simulate the role. <br>
+ * 1. Create a policy for each metadata object. <br>
+ * 2. Save role name in the Policy properties. <br>
+ * 3. Set `MANAGED_BY_GRAVITINO` label in the policy. <br>
+ * 4. For easy manage, each privilege will create a RangerPolicyItemAccess in the policy. <br>
+ * 5. The policy will only have one user, the user is the {OWNER} of the policy. <br>
+ * 6. The policy will not have group. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ createRangerRole(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ Boolean findAll;
+ try {
+ findAll =
+ role.securableObjects().stream()
+ .filter(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ return policy != null;
+ })
+ .count()
+ == role.securableObjects().size();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ return findAll;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple securable objects, so we didn't directly
+ * remove the policy. <br>
+ */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, remove the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult =
+ doRemoveSecurableObject(role.name(), (RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult =
+ doUpdateSecurableObject(role.name(), (RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object. If the metadata object doesn't have
+ * owner, then the preOwner will be null and newOwner will be not null.
+ * @param newOwner The new owner of the metadata object. If the metadata object already have
+ * owner, then the preOwner and newOwner will not be null.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ // 1. Set the owner of the metadata object
+ // 2. Transfer the ownership from preOwner to newOwner of the metadata object
+ check(newOwner != null, "The newOwner must be not null");
+
+ RangerPolicy policy = findManagedPolicy(metadataObject);
+ if (policy != null) {
+ policy.getPolicyItems().stream()
+ .filter(
+ policyItem -> {
+ return policyItem.getAccesses().stream()
+ .allMatch(
+ policyItemAccess -> {
+ return ownerPrivileges.contains(policyItemAccess.getType());
+ });
+ })
+ .forEach(
+ policyItem -> {
+ if (preOwner != null) {
+ if (preOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().removeIf(preOwner.name()::equals);
+ } else {
+ policyItem.getGroups().removeIf(preOwner.name()::equals);
+ }
+ }
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ });
+ } else {
+ policy = new RangerPolicy();
+ policy.setService(rangerServiceName);
+ policy.setName(metadataObject.fullName());
+ policy.setPolicyLabels(Lists.newArrayList(MANAGED_BY_GRAVITINO));
+
+ List<String> nsMetadataObject =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ if (nsMetadataObject.size() > 4) {
+ // The max level of the securable object is `catalog.db.table.column`
+ throw new RuntimeException("The securable object than 4");
+ }
+ nsMetadataObject.remove(0); // remove `catalog`
+
+ for (int i = 0; i < nsMetadataObject.size(); i++) {
+ RangerPolicy.RangerPolicyResource policyResource =
+ new RangerPolicy.RangerPolicyResource(nsMetadataObject.get(i));
+ policy
+ .getResources()
+ .put(
+ i == 0
+ ? RangerDefines.RESOURCE_DATABASE
+ : i == 1 ? RangerDefines.RESOURCE_TABLE : RangerDefines.RESOURCE_COLUMN,
+ policyResource);
+ }
+
+ RangerPolicy finalPolicy = policy;
+ ownerPrivileges.stream()
+ .forEach(
+ ownerPrivilege -> {
+ RangerPolicy.RangerPolicyItem policyItem = new RangerPolicy.RangerPolicyItem();
+ policyItem
+ .getAccesses()
+ .add(new RangerPolicy.RangerPolicyItemAccess(ownerPrivilege));
+ if (newOwner != null) {
+ if (newOwner.type() == Owner.Type.USER) {
+ policyItem.getUsers().add(newOwner.name());
+ } else {
+ policyItem.getGroups().add(newOwner.name());
+ }
+ }
+ finalPolicy.getPolicyItems().add(policyItem);
+ });
+ }
+ try {
+ if (policy.getId() == null) {
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to set the user.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user is not exist, then create it.
+ onUserAdded(user);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy does not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilegeName -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(
+ rangerPrivilegeName))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Because one Ranger policy maybe contain multiple Gravitino securable objects, <br>
+ * So we need to find the corresponding policy item mapping to remove the user.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the group. <br>
+ * 1. Create a group in the Ranger if the group is not exist. <br>
+ * 2. Create a role in the Ranger if the role is not exist. <br>
+ * 3. Add this group to the role. <br>
+ * 4. Add the role to the policy item base the metadata object. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param group The group to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToGroup(List<Role> roles, Group group) throws RuntimeException {
+ // If the group is not exist, then create it.
+ onGroupAdded(group);
+
+ AtomicReference<Boolean> execResult = new AtomicReference<>(Boolean.TRUE);
+ roles.stream()
+ .forEach(
+ role -> {
+ createRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+
+ role.securableObjects().stream()
+ .forEach(
+ securableObject -> {
+ RangerPolicy policy = findManagedPolicy(securableObject);
+ if (policy == null) {
+ LOG.warn(
+ "The policy is not exist for the securable object({})",
+ securableObject);
+ execResult.set(Boolean.FALSE);
+ return;
+ }
+
+ securableObject.privileges().stream()
+ .forEach(
+ privilege -> {
+ mapPrivileges
+ .getOrDefault(privilege.name(), Collections.emptySet())
+ .stream()
+ .forEach(
+ rangerPrivilege -> {
+ policy.getPolicyItems().stream()
+ .forEach(
+ policyItem -> {
+ if (policyItem.getAccesses().stream()
+ .anyMatch(
+ policyItemAccess ->
+ policyItemAccess
+ .getType()
+ .equals(rangerPrivilege))) {
+ if (!policyItem
+ .getRoles()
+ .contains(role.name())) {
+ policyItem.getRoles().add(role.name());
+ }
+ }
+ });
+ try {
+ rangerClient.updatePolicy(policy.getId(), policy);
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ });
+ });
+ });
+ });
+ if (!execResult.get()) {
+ return Boolean.FALSE;
+ }
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRevokedRolesFromGroup(List<Role> roles, Group group) throws RuntimeException {
+ roles.stream()
+ .forEach(
+ role -> {
+ checkRangerRole(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ createGrantRevokeRoleRequest(role.name(), null, group.name());
+ try {
+ rangerClient.revokeRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAdded(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() > 0) {
+ LOG.warn("The user({}) is already exist in the Ranger!", user.name());
+ return Boolean.FALSE;
+ }
+
+ VXUser rangerUser = VXUser.builder().withName(user.name()).withDescription(user.name()).build();
+ return rangerClient.createUser(rangerUser);
+ }
+
+ @Override
+ public Boolean onUserRemoved(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ rangerClient.deleteUser(list.getList().get(0).getId());
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onUserAcquired(User user) throws RuntimeException {
+ VXUserList list = rangerClient.searchUser(ImmutableMap.of("name", user.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The user({}) is not exist in the Ranger!", user);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onGroupAdded(Group group) throws RuntimeException {
+ return rangerClient.createGroup(VXGroup.builder().withName(group.name()).build());
+ }
+
+ @Override
+ public Boolean onGroupRemoved(Group group) throws RuntimeException {
+ VXGroupList list = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (list.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return rangerClient.deleteGroup(list.getList().get(0).getId());
+ }
+
+ @Override
+ public Boolean onGroupAcquired(Group group) {
+ VXGroupList vxGroupList = rangerClient.searchGroup(ImmutableMap.of("name", group.name()));
+ if (vxGroupList.getListSize() == 0) {
+ LOG.warn("The group({}) is not exist in the Ranger!", group);
+ return Boolean.FALSE;
+ }
+ return Boolean.TRUE;
+ }
+
+ private boolean checkRangerRole(String roleName) throws AuthorizationPluginException {
+ try {
+ rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ throw new AuthorizationPluginException(e);
+ }
+ return true;
+ }
+
+ private GrantRevokeRoleRequest createGrantRevokeRoleRequest(
+ String roleName, String userName, String groupName) {
+ Set<String> users;
+ if (userName == null || userName.isEmpty()) {
+ users = new HashSet<>();
+ } else {
+ users = new HashSet<>(Arrays.asList(userName));
+ }
+ Set<String> groups;
+ if (groupName == null || groupName.isEmpty()) {
+ groups = new HashSet<>();
+ } else {
+ groups = new HashSet<>(Arrays.asList(groupName));
+ }
+
+ GrantRevokeRoleRequest roleRequest = new GrantRevokeRoleRequest();
+ roleRequest.setUsers(users);
+ roleRequest.setGroups(groups);
+ roleRequest.setGrantor(RANGER_ADMIN_NAME);
+ roleRequest.setTargetRoles(new HashSet<>(Arrays.asList(roleName)));
+ return roleRequest;
+ }
+
+ /** Create a Ranger role if the role is not exist. */
+ private RangerRole createRangerRole(String roleName) {
+ RangerRole rangerRole = null;
+ try {
+ rangerRole = rangerClient.getRole(roleName, RANGER_ADMIN_NAME, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // ignore exception, If the role is not exist, then create it.
+ }
+ try {
+ if (rangerRole == null) {
+ rangerRole = new RangerRole(roleName, MANAGED_BY_GRAVITINO, null, null, null);
+ rangerClient.createRole(rangerServiceName, rangerRole);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+ return rangerRole;
+ }
+
+ /**
+ * Find the managed policy for the metadata object.
+ *
+ * @param metadataObject The metadata object to find the managed policy.
+ * @return The managed policy for the metadata object.
+ */
+ @VisibleForTesting
+ public RangerPolicy findManagedPolicy(MetadataObject metadataObject)
+ throws AuthorizationPluginException {
+ List<String> nsMetadataObj =
+ Lists.newArrayList(SecurableObjects.DOT_SPLITTER.splitToList(metadataObject.fullName()));
+ nsMetadataObj.remove(0); // skip `catalog`
+ Map<String, String> policyFilter = new HashMap<>();
+ Map<String, String> preciseFilterKeysFilter = new HashMap<>();
+ policyFilter.put(RangerDefines.SEARCH_FILTER_SERVICE_NAME, this.rangerServiceName);
+ policyFilter.put(SearchFilter.POLICY_LABELS_PARTIAL, MANAGED_BY_GRAVITINO);
+ for (int i = 0; i < nsMetadataObj.size(); i++) {
+ policyFilter.put(policyFilterKeys.get(i), nsMetadataObj.get(i));
+ preciseFilterKeysFilter.put(policyPreciseFilterKeys.get(i), nsMetadataObj.get(i));
+ }
+
+ try {
+ List<RangerPolicy> policies = rangerClient.findPolicies(policyFilter);
+
+ if (!policies.isEmpty()) {
+ // Because Ranger doesn't support the precise filter, Ranger will return the policy meets
+ // the wildcard(*,?) conditions, just like `*.*.*` policy will match `db1.table1.column1`
+ // So we need to manual precise filter the policies.
+ policies =
+ policies.stream()
+ .filter(
+ policy ->
+ policy.getResources().entrySet().stream()
+ .allMatch(
+ entry ->
+ preciseFilterKeysFilter.containsKey(entry.getKey())
+ && entry.getValue().getValues().size() == 1
+ && entry
+ .getValue()
+ .getValues()
+ .contains(preciseFilterKeysFilter.get(entry.getKey()))))
+ .collect(Collectors.toList());
+ }
+
+ // Only return the policies that are delegate Gravitino management
+ if (policies.size() > 1) {
+ throw new AuthorizationPluginException(
+ "Each metadata object only have one Gravitino management enable policies.");
+ }
+
+ RangerPolicy policy = policies.size() == 1 ? policies.get(0) : null;
+ // Didn't contain duplicate privilege in the delegate Gravitino management policy
+ if (policy != null) {
+ policy.getPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDenyPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getRowFilterPolicyItems().forEach(this::checkPolicyItemAccess);
+ policy.getDataMaskPolicyItems().forEach(this::checkPolicyItemAccess);
+ }
+
+ return policy;
Review Comment:
This isn't correct
```
if (policies == null || policies.isEmpty()) {
return null;
}
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#3963] feat(core): Apache Ranger Hive authorization pushdown [gravitino]
Posted by "xunliu (via GitHub)" <gi...@apache.org>.
xunliu commented on code in PR #4515:
URL: https://github.com/apache/gravitino/pull/4515#discussion_r1724893759
##########
authorizations/authorization-ranger/src/main/java/org/apache/gravitino/authorization/ranger/RangerAuthorizationPlugin.java:
##########
@@ -0,0 +1,583 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.authorization.ranger;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.authorization.Group;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Role;
+import org.apache.gravitino.authorization.RoleChange;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.authorization.User;
+import org.apache.gravitino.authorization.ranger.reference.RangerDefines;
+import org.apache.gravitino.authorization.ranger.reference.VXGroup;
+import org.apache.gravitino.authorization.ranger.reference.VXGroupList;
+import org.apache.gravitino.authorization.ranger.reference.VXUser;
+import org.apache.gravitino.authorization.ranger.reference.VXUserList;
+import org.apache.gravitino.connector.AuthorizationPropertiesMeta;
+import org.apache.gravitino.connector.authorization.AuthorizationPlugin;
+import org.apache.gravitino.meta.AuditInfo;
+import org.apache.gravitino.meta.GroupEntity;
+import org.apache.gravitino.meta.UserEntity;
+import org.apache.gravitino.utils.PrincipalUtils;
+import org.apache.ranger.RangerServiceException;
+import org.apache.ranger.plugin.model.RangerPolicy;
+import org.apache.ranger.plugin.util.GrantRevokeRoleRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Ranger authorization operations plugin abstract class. <br>
+ * 1. For Ranger limit, The same metadata object only has a unique Ranger policy, So a Ranger policy
+ * maybe contains multiple Gravitino securable objects. <br>
+ * 2. For easy management, each Ranger privilege will create one RangerPolicyItemAccess in the
+ * policy. <br>
+ * 3. Ranger also have Role concept, and support adds multiple users or groups in the Ranger Role,
+ * So we can use the Ranger Role to implement the Gravitino Role. <br>
+ * 4. The Ranger policy also supports multiple users and groups, But we only use a user or group to
+ * implement Gravitino Owner concept. <br>
+ */
+public class RangerAuthorizationPlugin implements AuthorizationPlugin {
+ private static final Logger LOG = LoggerFactory.getLogger(RangerAuthorizationPlugin.class);
+
+ protected String catalogProvider;
+ protected String rangerServiceName;
+ protected RangerClientExtend rangerClient;
+ private RangerHelper rangerHelper;
+ @VisibleForTesting public final String rangerAdminName;
+
+ public RangerAuthorizationPlugin(String catalogProvider, Map<String, String> config) {
+ super();
+ this.catalogProvider = catalogProvider;
+ String rangerUrl = config.get(AuthorizationPropertiesMeta.RANGER_ADMIN_URL);
+ String authType = config.get(AuthorizationPropertiesMeta.RANGER_AUTH_TYPE);
+ rangerAdminName = config.get(AuthorizationPropertiesMeta.RANGER_USERNAME);
+ // Apache Ranger Password should be minimum 8 characters with min one alphabet and one numeric.
+ String password = config.get(AuthorizationPropertiesMeta.RANGER_PASSWORD);
+ rangerServiceName = config.get(AuthorizationPropertiesMeta.RANGER_SERVICE_NAME);
+ RangerHelper.check(rangerUrl != null, "Ranger admin URL is required");
+ RangerHelper.check(authType != null, "Ranger auth type is required");
+ RangerHelper.check(rangerAdminName != null, "Ranger username is required");
+ RangerHelper.check(password != null, "Ranger password is required");
+ RangerHelper.check(rangerServiceName != null, "Ranger service name is required");
+ rangerClient = new RangerClientExtend(rangerUrl, authType, rangerAdminName, password);
+ rangerHelper = new RangerHelper(this, catalogProvider);
+ }
+
+ /**
+ * Translate the privilege name to the corresponding privilege name in the underlying permission
+ *
+ * @param name The privilege name to translate
+ * @return The corresponding privilege name in the underlying permission system
+ */
+ public Set<String> translatePrivilege(Privilege.Name name) {
+ return rangerHelper.privilegesMapping.get(name);
+ }
+
+ @VisibleForTesting
+ public List<String> getOwnerPrivileges() {
+ return Lists.newArrayList(rangerHelper.ownerPrivileges);
+ }
+
+ /**
+ * Create a new role in the Ranger. <br>
+ * 1. Create a policy for metadata object. <br>
+ * 2. Save role name in the Policy items. <br>
+ */
+ @Override
+ public Boolean onRoleCreated(Role role) throws RuntimeException {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ return onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.addSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ }
+
+ @Override
+ public Boolean onRoleAcquired(Role role) throws RuntimeException {
+ return rangerHelper.checkRangerRole(role.name());
+ }
+
+ /** Remove the role name from the Ranger policy item, and delete this Role in the Ranger. <br> */
+ @Override
+ public Boolean onRoleDeleted(Role role) throws RuntimeException {
+ // First, remove the role in the Ranger policy
+ onRoleUpdated(
+ role,
+ role.securableObjects().stream()
+ .map(securableObject -> RoleChange.removeSecurableObject(role.name(), securableObject))
+ .toArray(RoleChange[]::new));
+ // Lastly, delete the role in the Ranger
+ try {
+ rangerClient.deleteRole(role.name(), rangerAdminName, rangerServiceName);
+ } catch (RangerServiceException e) {
+ // Ignore exception to support idempotent operation
+ LOG.warn("Ranger delete role: {} failed!", role, e);
+ }
+ return Boolean.TRUE;
+ }
+
+ @Override
+ public Boolean onRoleUpdated(Role role, RoleChange... changes) throws RuntimeException {
+ for (RoleChange change : changes) {
+ boolean execResult;
+ if (change instanceof RoleChange.AddSecurableObject) {
+ execResult = doAddSecurableObject((RoleChange.AddSecurableObject) change);
+ } else if (change instanceof RoleChange.RemoveSecurableObject) {
+ execResult = doRemoveSecurableObject((RoleChange.RemoveSecurableObject) change);
+ } else if (change instanceof RoleChange.UpdateSecurableObject) {
+ execResult = doUpdateSecurableObject((RoleChange.UpdateSecurableObject) change);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported role change type: "
+ + (change == null ? "null" : change.getClass().getSimpleName()));
+ }
+ if (!execResult) {
+ return Boolean.FALSE;
+ }
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Set or transfer the ownership of the metadata object. <br>
+ * 1. If the metadata object already has an owner, then transfer the ownership from preOwner to
+ * newOwner, The function params preOwner and newOwner don't equal null. <br>
+ * 2. If the metadata object doesn't have an owner, then set the owner to newOwner, The function
+ * params preOwner equal null and newOwner don't equal null. <br>
+ *
+ * @param metadataObject The metadata object to set the owner.
+ * @param preOwner The previous owner of the metadata object.
+ * @param newOwner The new owner of the metadata object.
+ */
+ @Override
+ public Boolean onOwnerSet(MetadataObject metadataObject, Owner preOwner, Owner newOwner)
+ throws RuntimeException {
+ RangerHelper.check(newOwner != null, "The newOwner must be not null");
+
+ if (newOwner != null) {
+ // Add the user or group to the Ranger
+ AuditInfo auditInfo =
+ AuditInfo.builder()
+ .withCreator(PrincipalUtils.getCurrentPrincipal().getName())
+ .withCreateTime(Instant.now())
+ .build();
+ if (newOwner.type() == Owner.Type.USER) {
+ UserEntity userEntity =
+ UserEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onUserAdded(userEntity);
+ } else {
+ GroupEntity groupEntity =
+ GroupEntity.builder()
+ .withId(1L)
+ .withName(newOwner.name())
+ .withRoleNames(Collections.emptyList())
+ .withRoleIds(Collections.emptyList())
+ .withAuditInfo(auditInfo)
+ .build();
+ onGroupAdded(groupEntity);
+ }
+ }
+
+ RangerPolicy policy = rangerHelper.findManagedPolicy(metadataObject);
+ try {
+ if (policy == null) {
+ policy = rangerHelper.addOwnerToNewPolicy(metadataObject, newOwner);
+ rangerClient.createPolicy(policy);
+ } else {
+ rangerHelper.updatePolicyOwner(policy, preOwner, newOwner);
+ rangerClient.updatePolicy(policy.getId(), policy);
+ }
+ } catch (RangerServiceException e) {
+ throw new RuntimeException(e);
+ }
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Grant the roles to the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Create a role in the Ranger if the role does not exist. <br>
+ * 3. Add this user to the role. <br>
+ *
+ * @param roles The roles to grant to the group.
+ * @param user The user to grant the roles.
+ */
+ @Override
+ public Boolean onGrantedRolesToUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.createRangerRoleIfNotExists(role.name());
+ GrantRevokeRoleRequest grantRevokeRoleRequest =
+ rangerHelper.createGrantRevokeRoleRequest(role.name(), user.name(), null);
+ try {
+ rangerClient.grantRole(rangerServiceName, grantRevokeRoleRequest);
+ } catch (RangerServiceException e) {
+ // ignore exception, support idempotent operation
+ LOG.warn("Grant role: {} to user: {} failed!", role, user, e);
+ }
+ });
+
+ return Boolean.TRUE;
+ }
+
+ /**
+ * Revoke the roles from the user. <br>
+ * 1. Create a user in the Ranger if the user does not exist. <br>
+ * 2. Check the role if it exists in the Ranger. <br>
+ * 3. Revoke this user from the role. <br>
+ *
+ * @param roles The roles to revoke the group.
+ * @param user The user to revoke the roles.
+ */
+ @Override
+ public Boolean onRevokedRolesFromUser(List<Role> roles, User user) throws RuntimeException {
+ // If the user does not exist, then create it.
+ onUserAdded(user);
+
+ roles.stream()
+ .forEach(
+ role -> {
+ rangerHelper.checkRangerRole(role.name());
Review Comment:
I think it would be safer.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org