Search in sources :

Example 96 with RangerPolicyResource

use of org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource in project ranger by apache.

the class RangerServiceResourceServiceBase method getServiceResourceElements.

Map<String, RangerPolicyResource> getServiceResourceElements(T xObj) {
    List<XXServiceResourceElement> resElementList = daoMgr.getXXServiceResourceElement().findByResourceId(xObj.getId());
    Map<String, RangerPolicy.RangerPolicyResource> resourceElements = new HashMap<String, RangerPolicy.RangerPolicyResource>();
    for (XXServiceResourceElement resElement : resElementList) {
        List<String> resValueMapList = daoMgr.getXXServiceResourceElementValue().findValuesByResElementId(resElement.getId());
        XXResourceDef xResDef = daoMgr.getXXResourceDef().getById(resElement.getResDefId());
        RangerPolicyResource policyRes = new RangerPolicyResource();
        policyRes.setIsExcludes(resElement.getIsExcludes());
        policyRes.setIsRecursive(resElement.getIsRecursive());
        policyRes.setValues(resValueMapList);
        resourceElements.put(xResDef.getName(), policyRes);
    }
    return resourceElements;
}
Also used : RangerPolicy(org.apache.ranger.plugin.model.RangerPolicy) HashMap(java.util.HashMap) RangerPolicyResource(org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource) XXResourceDef(org.apache.ranger.entity.XXResourceDef) XXServiceResourceElement(org.apache.ranger.entity.XXServiceResourceElement)

Example 97 with RangerPolicyResource

use of org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource in project ranger by apache.

the class RangerPolicyValidator method isValidResourceFlags.

boolean isValidResourceFlags(final Map<String, RangerPolicyResource> inputPolicyResources, final List<ValidationFailureDetails> failures, final List<RangerResourceDef> resourceDefs, final String serviceDefName, final String policyName, boolean isAdmin) {
    if (LOG.isDebugEnabled()) {
        LOG.debug(String.format("==> RangerPolicyValidator.isValidResourceFlags(%s, %s, %s, %s, %s, %s)", inputPolicyResources, failures, resourceDefs, serviceDefName, policyName, isAdmin));
    }
    boolean valid = true;
    if (resourceDefs == null) {
        LOG.debug("isValidResourceFlags: service Def is null");
    } else {
        Map<String, RangerPolicyResource> policyResources = getPolicyResourceWithLowerCaseKeys(inputPolicyResources);
        for (RangerResourceDef resourceDef : resourceDefs) {
            if (resourceDef == null) {
                ValidationErrorCode error = ValidationErrorCode.POLICY_VALIDATION_ERR_NULL_RESOURCE_DEF;
                failures.add(new ValidationFailureDetailsBuilder().field("resource-def").isAnInternalError().becauseOf(error.getMessage(serviceDefName)).errorCode(error.getErrorCode()).build());
                valid = false;
            } else if (StringUtils.isBlank(resourceDef.getName())) {
                ValidationErrorCode error = ValidationErrorCode.POLICY_VALIDATION_ERR_MISSING_RESOURCE_DEF_NAME;
                failures.add(new ValidationFailureDetailsBuilder().field("resource-def-name").isAnInternalError().becauseOf(error.getMessage(serviceDefName)).errorCode(error.getErrorCode()).build());
                valid = false;
            } else {
                String resourceName = resourceDef.getName().toLowerCase();
                RangerPolicyResource policyResource = policyResources.get(resourceName);
                if (policyResource == null) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("a policy-resource object for resource[" + resourceName + "] on policy [" + policyName + "] was null");
                    }
                } else {
                    // could be null
                    boolean excludesSupported = Boolean.TRUE.equals(resourceDef.getExcludesSupported());
                    // could be null
                    boolean policyResourceIsExcludes = Boolean.TRUE.equals(policyResource.getIsExcludes());
                    if (policyResourceIsExcludes && !excludesSupported) {
                        ValidationErrorCode error = ValidationErrorCode.POLICY_VALIDATION_ERR_EXCLUDES_NOT_SUPPORTED;
                        failures.add(new ValidationFailureDetailsBuilder().field("isExcludes").subField(resourceName).isSemanticallyIncorrect().becauseOf(error.getMessage(resourceName)).errorCode(error.getErrorCode()).build());
                        valid = false;
                    }
                    if (policyResourceIsExcludes && !isAdmin) {
                        ValidationErrorCode error = ValidationErrorCode.POLICY_VALIDATION_ERR_EXCLUDES_REQUIRES_ADMIN;
                        failures.add(new ValidationFailureDetailsBuilder().field("isExcludes").subField("isAdmin").isSemanticallyIncorrect().becauseOf(error.getMessage()).errorCode(error.getErrorCode()).build());
                        valid = false;
                    }
                    boolean recursiveSupported = Boolean.TRUE.equals(resourceDef.getRecursiveSupported());
                    boolean policyIsRecursive = Boolean.TRUE.equals(policyResource.getIsRecursive());
                    if (policyIsRecursive && !recursiveSupported) {
                        ValidationErrorCode error = ValidationErrorCode.POLICY_VALIDATION_ERR_RECURSIVE_NOT_SUPPORTED;
                        failures.add(new ValidationFailureDetailsBuilder().field("isRecursive").subField(resourceName).isSemanticallyIncorrect().becauseOf(error.getMessage(resourceName)).errorCode(error.getErrorCode()).build());
                        valid = false;
                    }
                }
            }
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug(String.format("<== RangerPolicyValidator.isValidResourceFlags(%s, %s, %s, %s, %s, %s): %s", inputPolicyResources, failures, resourceDefs, serviceDefName, policyName, isAdmin, valid));
    }
    return valid;
}
Also used : RangerPolicyResource(org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource) ValidationErrorCode(org.apache.ranger.plugin.errors.ValidationErrorCode) RangerResourceDef(org.apache.ranger.plugin.model.RangerServiceDef.RangerResourceDef)

Example 98 with RangerPolicyResource

use of org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource in project ranger by apache.

the class RangerPolicyValidator method isValidResourceValues.

boolean isValidResourceValues(Map<String, RangerPolicyResource> resourceMap, List<ValidationFailureDetails> failures, RangerServiceDef serviceDef) {
    if (LOG.isDebugEnabled()) {
        LOG.debug(String.format("==> RangerPolicyValidator.isValidResourceValues(%s, %s, %s)", resourceMap, failures, serviceDef));
    }
    boolean valid = true;
    Map<String, String> validationRegExMap = getValidationRegExes(serviceDef);
    for (Map.Entry<String, RangerPolicyResource> entry : resourceMap.entrySet()) {
        String name = entry.getKey();
        RangerPolicyResource policyResource = entry.getValue();
        if (policyResource != null) {
            if (CollectionUtils.isNotEmpty(policyResource.getValues())) {
                Set<String> resources = new HashSet<>(policyResource.getValues());
                for (String aValue : resources) {
                    if (StringUtils.isBlank(aValue)) {
                        policyResource.getValues().remove(aValue);
                    }
                }
            }
            if (CollectionUtils.isEmpty(policyResource.getValues())) {
                ValidationErrorCode error = ValidationErrorCode.POLICY_VALIDATION_ERR_MISSING_RESOURCE_LIST;
                if (LOG.isDebugEnabled()) {
                    LOG.debug(String.format("Resource list was empty or contains null: value[%s], resource-name[%s], service-def-name[%s]", policyResource.getValues(), name, serviceDef.getName()));
                }
                failures.add(new ValidationFailureDetailsBuilder().field("resource-values").subField(name).isMissing().becauseOf(error.getMessage(name)).errorCode(error.getErrorCode()).build());
                valid = false;
            }
            if (validationRegExMap.containsKey(name) && CollectionUtils.isNotEmpty(policyResource.getValues())) {
                String regEx = validationRegExMap.get(name);
                for (String aValue : policyResource.getValues()) {
                    if (!aValue.matches(regEx)) {
                        if (LOG.isDebugEnabled()) {
                            LOG.debug(String.format("Resource failed regex check: value[%s], resource-name[%s], regEx[%s], service-def-name[%s]", aValue, name, regEx, serviceDef.getName()));
                        }
                        ValidationErrorCode error = ValidationErrorCode.POLICY_VALIDATION_ERR_INVALID_RESOURCE_VALUE_REGEX;
                        failures.add(new ValidationFailureDetailsBuilder().field("resource-values").subField(name).isSemanticallyIncorrect().becauseOf(error.getMessage(aValue, name)).errorCode(error.getErrorCode()).build());
                        valid = false;
                    }
                }
            }
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug(String.format("<== RangerPolicyValidator.isValidResourceValues(%s, %s, %s): %s", resourceMap, failures, serviceDef, valid));
    }
    return valid;
}
Also used : RangerPolicyResource(org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource) ValidationErrorCode(org.apache.ranger.plugin.errors.ValidationErrorCode)

Example 99 with RangerPolicyResource

use of org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource in project ranger by apache.

the class RangerServiceAtlas method getDefaultRangerPolicies.

@Override
public List<RangerPolicy> getDefaultRangerPolicies() throws Exception {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> RangerServiceAtlas.getDefaultRangerPolicies()");
    }
    List<RangerPolicy> ret = super.getDefaultRangerPolicies();
    String adminUser = getStringConfig("atlas.admin.user", ADMIN_USERNAME_DEFAULT);
    String tagSyncUser = getStringConfig("atlas.rangertagsync.user", TAGSYNC_USERNAME_DEFAULT);
    boolean relationshipTypeAllowPublic = getBooleanConfig("atlas.default-policy.relationship-type.allow.public", true);
    for (RangerPolicy defaultPolicy : ret) {
        final Map<String, RangerPolicyResource> policyResources = defaultPolicy.getResources();
        // 1. add adminUser to every policyItem
        for (RangerPolicyItem defaultPolicyItem : defaultPolicy.getPolicyItems()) {
            defaultPolicyItem.getUsers().add(adminUser);
        }
        // 2. add a policy-item for rangertagsync user with 'entity-read' permission in the policy for 'entity-type'
        if (policyResources.containsKey(RESOURCE_ENTITY_TYPE) && !policyResources.containsKey(RESOURCE_CLASSIFICATION)) {
            RangerPolicyItem policyItemForTagSyncUser = new RangerPolicyItem();
            policyItemForTagSyncUser.setUsers(Collections.singletonList(tagSyncUser));
            policyItemForTagSyncUser.setGroups(Collections.singletonList(RangerPolicyEngine.GROUP_PUBLIC));
            policyItemForTagSyncUser.setAccesses(Collections.singletonList(new RangerPolicyItemAccess(ACCESS_TYPE_ENTITY_READ)));
            defaultPolicy.getPolicyItems().add(policyItemForTagSyncUser);
        }
        if (relationshipTypeAllowPublic) {
            // 3. add 'public' group in the policy for 'relationship-type',
            if (policyResources.containsKey(RangerServiceAtlas.RESOURCE_RELATIONSHIP_TYPE)) {
                for (RangerPolicyItem defaultPolicyItem : defaultPolicy.getPolicyItems()) {
                    defaultPolicyItem.getGroups().add(RangerPolicyEngine.GROUP_PUBLIC);
                }
            }
        }
        if (defaultPolicy.getName().contains("all") && policyResources.containsKey(RangerServiceAtlas.RESOURCE_ENTITY_TYPE) && StringUtils.isNotBlank(lookUpUser) && !policyResources.containsKey(RESOURCE_CLASSIFICATION)) {
            RangerPolicyItem policyItemForLookupUser = new RangerPolicyItem();
            policyItemForLookupUser.setUsers(Collections.singletonList(lookUpUser));
            policyItemForLookupUser.setAccesses(Collections.singletonList(new RangerPolicyItemAccess(ACCESS_TYPE_ENTITY_READ)));
            policyItemForLookupUser.setDelegateAdmin(false);
            defaultPolicy.getPolicyItems().add(policyItemForLookupUser);
        }
        // add a policy-item for rangertagsync user with 'type-read' permission in the policy for 'type-category'
        if (policyResources.containsKey(RangerServiceAtlas.RESOURCE_TYPE_CATEGORY)) {
            RangerPolicyItem policyItemTypeReadForAll = new RangerPolicyItem();
            policyItemTypeReadForAll.setGroups(Collections.singletonList(RangerPolicyEngine.GROUP_PUBLIC));
            policyItemTypeReadForAll.setAccesses(Collections.singletonList(new RangerPolicyItemAccess(ACCESS_TYPE_TYPE_READ)));
            defaultPolicy.getPolicyItems().add(policyItemTypeReadForAll);
        }
    }
    // 4.add new policy for public group with entity-read, entity-create, entity-update, entity-delete for  __AtlasUserProfile, __AtlasUserSavedSearch entity type
    RangerPolicy searchFeaturePolicy = getSearchFeaturePolicy();
    ret.add(searchFeaturePolicy);
    if (LOG.isDebugEnabled()) {
        LOG.debug("<== RangerServiceAtlas.getDefaultRangerPolicies()");
    }
    return ret;
}
Also used : RangerPolicy(org.apache.ranger.plugin.model.RangerPolicy) RangerPolicyResource(org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource) RangerPolicyItemAccess(org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemAccess) RangerPolicyItem(org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem)

Example 100 with RangerPolicyResource

use of org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource in project ranger by apache.

the class ServiceREST method secureGrantAccess.

@POST
@Path("/secure/services/grant/{serviceName}")
@Produces({ "application/json", "application/xml" })
public RESTResponse secureGrantAccess(@PathParam("serviceName") String serviceName, GrantRevokeRequest grantRequest, @Context HttpServletRequest request) throws Exception {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> ServiceREST.secureGrantAccess(" + serviceName + ", " + grantRequest + ")");
    }
    RESTResponse ret = new RESTResponse();
    RangerPerfTracer perf = null;
    bizUtil.blockAuditorRoleUser();
    if (grantRequest != null) {
        if (serviceUtil.isValidService(serviceName, request)) {
            try {
                if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
                    perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.scureGrantAccess(serviceName=" + serviceName + ")");
                }
                XXService xService = daoManager.getXXService().findByName(serviceName);
                XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(xService.getType());
                RangerService rangerService = svcStore.getServiceByName(serviceName);
                String loggedInUser = bizUtil.getCurrentUserLoginId();
                boolean hasAdminPrivilege = bizUtil.isAdmin() || bizUtil.isUserServiceAdmin(rangerService, loggedInUser) || bizUtil.isUserAllowedForGrantRevoke(rangerService, loggedInUser);
                validateGrantRevokeRequest(grantRequest, hasAdminPrivilege, loggedInUser);
                String userName = grantRequest.getGrantor();
                Set<String> userGroups = grantRequest.getGrantorGroups();
                String ownerUser = grantRequest.getOwnerUser();
                RangerAccessResource resource = new RangerAccessResourceImpl(StringUtil.toStringObjectMap(grantRequest.getResource()), ownerUser);
                Set<String> accessTypes = grantRequest.getAccessTypes();
                String zoneName = getRangerAdminZoneName(serviceName, grantRequest);
                boolean isAllowed = false;
                if (StringUtils.equals(xServiceDef.getImplclassname(), EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME)) {
                    if (bizUtil.isKeyAdmin() || bizUtil.isUserAllowedForGrantRevoke(rangerService, loggedInUser)) {
                        isAllowed = true;
                    }
                } else {
                    isAllowed = bizUtil.isUserRangerAdmin(userName) || bizUtil.isUserServiceAdmin(rangerService, userName) || hasAdminAccess(serviceName, zoneName, userName, userGroups, resource, accessTypes);
                }
                if (isAllowed) {
                    RangerPolicy policy = getExactMatchPolicyForResource(serviceName, resource, zoneName, userName);
                    if (policy != null) {
                        boolean policyUpdated = false;
                        policyUpdated = ServiceRESTUtil.processGrantRequest(policy, grantRequest);
                        if (policyUpdated) {
                            policy.setZoneName(zoneName);
                            svcStore.updatePolicy(policy);
                        } else {
                            LOG.error("processSecureGrantRequest processing failed");
                            throw new Exception("processSecureGrantRequest processing failed");
                        }
                    } else {
                        policy = new RangerPolicy();
                        policy.setService(serviceName);
                        // TODO: better policy name
                        policy.setName("grant-" + System.currentTimeMillis());
                        policy.setDescription("created by grant");
                        policy.setIsAuditEnabled(grantRequest.getEnableAudit());
                        policy.setCreatedBy(userName);
                        Map<String, RangerPolicyResource> policyResources = new HashMap<String, RangerPolicyResource>();
                        Set<String> resourceNames = resource.getKeys();
                        if (!CollectionUtils.isEmpty(resourceNames)) {
                            for (String resourceName : resourceNames) {
                                RangerPolicyResource policyResource = new RangerPolicyResource((String) resource.getValue(resourceName));
                                policyResource.setIsRecursive(grantRequest.getIsRecursive());
                                policyResources.put(resourceName, policyResource);
                            }
                        }
                        policy.setResources(policyResources);
                        RangerPolicyItem policyItem = new RangerPolicyItem();
                        policyItem.setDelegateAdmin(grantRequest.getDelegateAdmin());
                        policyItem.getUsers().addAll(grantRequest.getUsers());
                        policyItem.getGroups().addAll(grantRequest.getGroups());
                        policyItem.getRoles().addAll(grantRequest.getRoles());
                        for (String accessType : grantRequest.getAccessTypes()) {
                            policyItem.getAccesses().add(new RangerPolicyItemAccess(accessType, Boolean.TRUE));
                        }
                        policy.getPolicyItems().add(policyItem);
                        policy.setZoneName(zoneName);
                        svcStore.createPolicy(policy);
                    }
                } else {
                    LOG.error("secureGrantAccess(" + serviceName + ", " + grantRequest + ") failed as User doesn't have permission to grant Policy");
                    throw restErrorUtil.createGrantRevokeRESTException("User doesn't have necessary permission to grant access");
                }
            } catch (WebApplicationException excp) {
                throw excp;
            } catch (Throwable excp) {
                LOG.error("secureGrantAccess(" + serviceName + ", " + grantRequest + ") failed", excp);
                throw restErrorUtil.createRESTException(excp.getMessage());
            } finally {
                RangerPerfTracer.log(perf);
            }
            ret.setStatusCode(RESTResponse.STATUS_SUCCESS);
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("<== ServiceREST.secureGrantAccess(" + serviceName + ", " + grantRequest + "): " + ret);
    }
    return ret;
}
Also used : XXServiceDef(org.apache.ranger.entity.XXServiceDef) WebApplicationException(javax.ws.rs.WebApplicationException) RangerPerfTracer(org.apache.ranger.plugin.util.RangerPerfTracer) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) RangerPolicyResource(org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource) VXString(org.apache.ranger.view.VXString) RangerPolicyItem(org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException) JsonSyntaxException(com.google.gson.JsonSyntaxException) RangerPolicy(org.apache.ranger.plugin.model.RangerPolicy) RangerAccessResourceImpl(org.apache.ranger.plugin.policyengine.RangerAccessResourceImpl) RESTResponse(org.apache.ranger.admin.client.datatype.RESTResponse) RangerPolicyItemAccess(org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemAccess) RangerService(org.apache.ranger.plugin.model.RangerService) XXService(org.apache.ranger.entity.XXService) RangerAccessResource(org.apache.ranger.plugin.policyengine.RangerAccessResource) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Aggregations

RangerPolicyResource (org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource)101 HashMap (java.util.HashMap)65 RangerPolicy (org.apache.ranger.plugin.model.RangerPolicy)64 ArrayList (java.util.ArrayList)50 Test (org.junit.Test)43 RangerPolicyItem (org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem)35 RangerPolicyItemAccess (org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemAccess)32 Date (java.util.Date)26 RangerService (org.apache.ranger.plugin.model.RangerService)23 VXString (org.apache.ranger.view.VXString)18 RangerPolicyItemCondition (org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemCondition)17 VXAuditMap (org.apache.ranger.view.VXAuditMap)15 VXResource (org.apache.ranger.view.VXResource)15 RangerResourceDef (org.apache.ranger.plugin.model.RangerServiceDef.RangerResourceDef)12 LinkedHashMap (java.util.LinkedHashMap)10 XXServiceDef (org.apache.ranger.entity.XXServiceDef)8 RangerServiceDef (org.apache.ranger.plugin.model.RangerServiceDef)8 RangerPerfTracer (org.apache.ranger.plugin.util.RangerPerfTracer)8 ServicePolicies (org.apache.ranger.plugin.util.ServicePolicies)8 RangerServiceResource (org.apache.ranger.plugin.model.RangerServiceResource)7