Search in sources :

Example 6 with RangerRole

use of org.apache.ranger.plugin.model.RangerRole in project ranger by apache.

the class RolePredicateUtil method addPredicateForRoleName.

private Predicate addPredicateForRoleName(final String roleName, List<Predicate> predicates) {
    if (StringUtils.isEmpty(roleName)) {
        return null;
    }
    Predicate ret = new Predicate() {

        @Override
        public boolean evaluate(Object object) {
            if (object == null) {
                return false;
            }
            boolean ret = false;
            if (object instanceof RangerRole) {
                RangerRole role = (RangerRole) object;
                ret = StringUtils.equals(role.getName(), roleName);
                if (!ret) {
                    List<RangerRole.RoleMember> roles = role.getRoles();
                    for (RangerRole.RoleMember member : roles) {
                        ret = StringUtils.equals(role.getName(), roleName);
                        if (ret) {
                            break;
                        }
                    }
                }
            }
            return ret;
        }
    };
    if (predicates != null) {
        predicates.add(ret);
    }
    return ret;
}
Also used : RangerRole(org.apache.ranger.plugin.model.RangerRole) Predicate(org.apache.commons.collections.Predicate)

Example 7 with RangerRole

use of org.apache.ranger.plugin.model.RangerRole in project ranger by apache.

the class RolePredicateUtil method addPredicateForUserName.

private Predicate addPredicateForUserName(final String userName, List<Predicate> predicates) {
    if (StringUtils.isEmpty(userName)) {
        return null;
    }
    Predicate ret = new Predicate() {

        @Override
        public boolean evaluate(Object object) {
            if (object == null) {
                return false;
            }
            boolean ret = false;
            if (object instanceof RangerRole) {
                RangerRole role = (RangerRole) object;
                List<RangerRole.RoleMember> users = role.getUsers();
                for (RangerRole.RoleMember member : users) {
                    ret = StringUtils.equals(member.getName(), userName);
                    if (ret) {
                        break;
                    }
                }
            }
            return ret;
        }
    };
    if (predicates != null) {
        predicates.add(ret);
    }
    return ret;
}
Also used : RangerRole(org.apache.ranger.plugin.model.RangerRole) Predicate(org.apache.commons.collections.Predicate)

Example 8 with RangerRole

use of org.apache.ranger.plugin.model.RangerRole in project ranger by apache.

the class RangerRoleValidator method isValid.

boolean isValid(RangerRole rangerRole, Action action, List<ValidationFailureDetails> failures) {
    if (LOG.isDebugEnabled()) {
        LOG.debug(String.format("==> RangerRoleValidator.isValid(%s, %s, %s)", rangerRole, action, failures));
    }
    boolean valid = true;
    if (rangerRole == null) {
        ValidationErrorCode error = ValidationErrorCode.ROLE_VALIDATION_ERR_NULL_RANGER_ROLE_OBJECT;
        failures.add(new ValidationFailureDetailsBuilder().isAnInternalError().isMissing().becauseOf(error.getMessage()).errorCode(error.getErrorCode()).build());
        valid = false;
    } else {
        String roleName = rangerRole.getName();
        if (StringUtils.isEmpty(roleName)) {
            ValidationErrorCode error = ValidationErrorCode.ROLE_VALIDATION_ERR_NULL_RANGER_ROLE_NAME;
            failures.add(new ValidationFailureDetailsBuilder().field("name").isMissing().becauseOf(error.getMessage()).errorCode(error.getErrorCode()).build());
            valid = false;
        }
        Long id = rangerRole.getId();
        RangerRole existingRangerRole = null;
        if (null != id) {
            existingRangerRole = getRangerRole(id);
        }
        if (action == Action.CREATE) {
            if (existingRangerRole != null) {
                String existingRoleName = existingRangerRole.getName();
                if (roleName.equals(existingRoleName)) {
                    ValidationErrorCode error = ValidationErrorCode.ROLE_VALIDATION_ERR_ROLE_NAME_CONFLICT;
                    failures.add(new ValidationFailureDetailsBuilder().field("name").isSemanticallyIncorrect().becauseOf(error.getMessage(existingRoleName)).errorCode(error.getErrorCode()).build());
                    valid = false;
                }
            }
        } else if (action == Action.UPDATE) {
            // id is ignored for CREATE
            if (id == null) {
                ValidationErrorCode error = ValidationErrorCode.ROLE_VALIDATION_ERR_MISSING_FIELD;
                failures.add(new ValidationFailureDetailsBuilder().field("id").isMissing().becauseOf(error.getMessage(id)).errorCode(error.getErrorCode()).build());
                valid = false;
            }
            if (existingRangerRole == null) {
                ValidationErrorCode error = ValidationErrorCode.ROLE_VALIDATION_ERR_INVALID_ROLE_ID;
                failures.add(new ValidationFailureDetailsBuilder().field("id").isSemanticallyIncorrect().becauseOf(error.getMessage(id)).errorCode(error.getErrorCode()).build());
                valid = false;
            }
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug(String.format("<== RangerRoleValidator.isValid(%s, %s, %s): %s", rangerRole, action, failures, valid));
    }
    return valid;
}
Also used : RangerRole(org.apache.ranger.plugin.model.RangerRole) ValidationErrorCode(org.apache.ranger.plugin.errors.ValidationErrorCode)

Example 9 with RangerRole

use of org.apache.ranger.plugin.model.RangerRole in project ranger by apache.

the class SampleClient method main.

@SuppressWarnings("static-access")
public static void main(String[] args) throws RangerServiceException {
    Gson gsonBuilder = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").setPrettyPrinting().create();
    Options options = new Options();
    Option host = OptionBuilder.hasArgs(1).isRequired().withLongOpt("host").withDescription("hostname").create('h');
    Option auth = OptionBuilder.hasArgs(1).isRequired().withLongOpt("authType").withDescription("Authentication Type").create('k');
    Option user = OptionBuilder.hasArgs(1).isRequired().withLongOpt("user").withDescription("username").create('u');
    Option pass = OptionBuilder.hasArgs(1).isRequired().withLongOpt("pass").withDescription("password").create('p');
    Option conf = OptionBuilder.hasArgs(1).withLongOpt("config").withDescription("configuration").create('c');
    options.addOption(host);
    options.addOption(auth);
    options.addOption(user);
    options.addOption(pass);
    options.addOption(conf);
    CommandLineParser parser = new BasicParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        throw new RuntimeException(e);
    }
    String hostName = cmd.getOptionValue('h');
    String userName = cmd.getOptionValue('u');
    String password = cmd.getOptionValue('p');
    String cfg = cmd.getOptionValue('c');
    String authType = cmd.getOptionValue('k');
    RangerClient rangerClient = new RangerClient(hostName, authType, userName, password, cfg);
    String serviceDefName = "sampleServiceDef";
    String serviceName = "sampleService";
    String policyName = "samplePolicy";
    String roleName = "sampleRole";
    Map<String, String> filter = Collections.emptyMap();
    /*
        Create a new Service Definition
         */
    RangerServiceDef.RangerServiceConfigDef config = new RangerServiceDef.RangerServiceConfigDef();
    config.setItemId(1L);
    config.setName("sampleConfig");
    config.setType("string");
    List<RangerServiceDef.RangerServiceConfigDef> configs = Collections.singletonList(config);
    RangerServiceDef.RangerAccessTypeDef accessType = new RangerServiceDef.RangerAccessTypeDef();
    accessType.setItemId(1L);
    accessType.setName("sampleAccess");
    List<RangerServiceDef.RangerAccessTypeDef> accessTypes = Collections.singletonList(accessType);
    RangerServiceDef.RangerResourceDef resourceDef = new RangerServiceDef.RangerResourceDef();
    resourceDef.setItemId(1L);
    resourceDef.setName("root");
    resourceDef.setType("string");
    List<RangerServiceDef.RangerResourceDef> resourceDefs = Collections.singletonList(resourceDef);
    RangerServiceDef serviceDef = new RangerServiceDef();
    serviceDef.setName(serviceDefName);
    serviceDef.setConfigs(configs);
    serviceDef.setAccessTypes(accessTypes);
    serviceDef.setResources(resourceDefs);
    RangerServiceDef createdServiceDef = rangerClient.createServiceDef(serviceDef);
    LOG.info("New Service Definition created successfully {}", gsonBuilder.toJson(createdServiceDef));
    /*
        Create a new Service
         */
    RangerService service = new RangerService();
    service.setType(serviceDefName);
    service.setName(serviceName);
    RangerService createdService = rangerClient.createService(service);
    LOG.info("New Service created successfully {}", gsonBuilder.toJson(createdService));
    /*
        All Services
         */
    List<RangerService> services = rangerClient.findServices(filter);
    String allServiceNames = "";
    for (RangerService svc : services) {
        allServiceNames = allServiceNames.concat(svc.getName() + " ");
    }
    LOG.info("List of Services : {}", allServiceNames);
    /*
        Policy Management
         */
    /*
        Create a new Policy
         */
    Map<String, RangerPolicy.RangerPolicyResource> resource = Collections.singletonMap("root", new RangerPolicy.RangerPolicyResource(Collections.singletonList("/path/to/sample/resource"), false, false));
    RangerPolicy policy = new RangerPolicy();
    policy.setService(serviceName);
    policy.setName(policyName);
    policy.setResources(resource);
    RangerPolicy createdPolicy = rangerClient.createPolicy(policy);
    LOG.info("New Policy created successfully {}", gsonBuilder.toJson(createdPolicy));
    /*
        Get a policy by name
         */
    RangerPolicy fetchedPolicy = rangerClient.getPolicy(serviceName, policyName);
    LOG.info("Policy: {} fetched {}", policyName, gsonBuilder.toJson(fetchedPolicy));
    /*
        Delete a policy
         */
    rangerClient.deletePolicy(serviceName, policyName);
    LOG.info("Policy {} successfully deleted", policyName);
    /*
        Delete a Service
         */
    rangerClient.deleteService(serviceName);
    LOG.info("Service {} successfully deleted", serviceName);
    /*
        Delete a Service Definition
         */
    rangerClient.deleteServiceDef(serviceDefName);
    LOG.info("Service Definition {} successfully deleted", serviceDefName);
    /*
        Role Management
         */
    /*
        Create a role in Ranger
         */
    RangerRole sampleRole = new RangerRole();
    sampleRole.setName(roleName);
    sampleRole.setDescription("Sample Role");
    sampleRole.setUsers(Collections.singletonList(new RangerRole.RoleMember(null, true)));
    sampleRole = rangerClient.createRole(serviceName, sampleRole);
    LOG.info("New Role successfully created {}", gsonBuilder.toJson(sampleRole));
    /*
        Update a role in Ranger
         */
    sampleRole.setDescription("Updated Sample Role");
    RangerRole updatedRole = rangerClient.updateRole(sampleRole.getId(), sampleRole);
    LOG.info("Role {} successfully updated {}", roleName, gsonBuilder.toJson(updatedRole));
    /*
        Get all roles in Ranger
         */
    List<RangerRole> allRoles = rangerClient.findRoles(filter);
    LOG.info("List of Roles {}", gsonBuilder.toJson(allRoles));
    String allRoleNames = "";
    for (RangerRole role : allRoles) {
        allRoleNames = allRoleNames.concat(role.getName() + " ");
    }
    LOG.info("List of Roles : {}", allRoleNames);
    /*
        Delete a role in Ranger
         */
    rangerClient.deleteRole(roleName, userName, serviceName);
    LOG.info("Role {} successfully deleted", roleName);
}
Also used : Gson(com.google.gson.Gson) RangerPolicy(org.apache.ranger.plugin.model.RangerPolicy) RangerRole(org.apache.ranger.plugin.model.RangerRole) RangerClient(org.apache.ranger.RangerClient) RangerService(org.apache.ranger.plugin.model.RangerService) GsonBuilder(com.google.gson.GsonBuilder) RangerServiceDef(org.apache.ranger.plugin.model.RangerServiceDef)

Example 10 with RangerRole

use of org.apache.ranger.plugin.model.RangerRole in project ranger by apache.

the class RoleREST method getRoleIfAccessible.

private RangerRole getRoleIfAccessible(String roleName, String serviceName, String userName, Set<String> userGroups) {
    /* If userName (execUser) is not same as logged in user then check
            * If logged-in user is not ranger admin/service admin/service user, then deny the operation
                * effective User is execUser
         * else
            * effective user is logged-in user
         * If effective user is ranger admin/has role admin privilege, then allow the operation
         * else deny the operation
         */
    RangerRole existingRole;
    String effectiveUser;
    UserSessionBase usb = ContextUtil.getCurrentUserSession();
    String loggedInUser = usb != null ? usb.getLoginId() : null;
    if (!StringUtil.equals(userName, loggedInUser)) {
        if (!bizUtil.isUserRangerAdmin(loggedInUser) && !userIsSrvAdmOrSrvUser(serviceName, loggedInUser)) {
            LOG.error("User does not have permission for this operation");
            return null;
        }
        effectiveUser = userName != null ? userName : loggedInUser;
    } else {
        effectiveUser = loggedInUser;
    }
    try {
        if (!bizUtil.isUserRangerAdmin(effectiveUser)) {
            existingRole = roleStore.getRole(roleName);
            ensureRoleAccess(effectiveUser, userGroups, existingRole);
        } else {
            existingRole = roleStore.getRole(roleName);
        }
    } catch (Exception ex) {
        LOG.error(ex.getMessage());
        return null;
    }
    return existingRole;
}
Also used : RangerRole(org.apache.ranger.plugin.model.RangerRole) UserSessionBase(org.apache.ranger.common.UserSessionBase)

Aggregations

RangerRole (org.apache.ranger.plugin.model.RangerRole)37 Predicate (org.apache.commons.collections.Predicate)7 ArrayList (java.util.ArrayList)6 HashSet (java.util.HashSet)5 UserGroupInformation (org.apache.hadoop.security.UserGroupInformation)5 IOException (java.io.IOException)4 SemanticException (org.apache.hadoop.hive.ql.parse.SemanticException)4 HiveAccessControlException (org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAccessControlException)4 HiveAuthzPluginException (org.apache.hadoop.hive.ql.security.authorization.plugin.HiveAuthzPluginException)4 RESTResponse (org.apache.ranger.admin.client.datatype.RESTResponse)4 RangerAccessResult (org.apache.ranger.plugin.policyengine.RangerAccessResult)4 RangerRoles (org.apache.ranger.plugin.util.RangerRoles)4 UserSessionBase (org.apache.ranger.common.UserSessionBase)3 Gson (com.google.gson.Gson)2 GsonBuilder (com.google.gson.GsonBuilder)2 ClientResponse (com.sun.jersey.api.client.ClientResponse)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 PrivilegedAction (java.security.PrivilegedAction)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2