Search in sources :

Example 61 with RangerPolicy

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

the class ServiceREST method deletePoliciesForResource.

private void deletePoliciesForResource(List<String> sourceServices, List<String> destinationServices, String resource, HttpServletRequest request, List<RangerPolicy> exportPolicies) {
    int totalDeletedPilicies = 0;
    if (CollectionUtils.isNotEmpty(sourceServices) && CollectionUtils.isNotEmpty(destinationServices)) {
        Set<String> exportedPolicyNames = new HashSet<String>();
        if (CollectionUtils.isNotEmpty(exportPolicies)) {
            for (RangerPolicy rangerPolicy : exportPolicies) {
                if (rangerPolicy != null) {
                    exportedPolicyNames.add(rangerPolicy.getName());
                }
            }
        }
        for (int i = 0; i < sourceServices.size(); i++) {
            if (!destinationServices.get(i).isEmpty()) {
                RangerPolicyList servicePolicies = null;
                servicePolicies = getServicePoliciesByName(destinationServices.get(i), request);
                if (servicePolicies != null) {
                    List<RangerPolicy> rangerPolicyList = servicePolicies.getPolicies();
                    if (CollectionUtils.isNotEmpty(rangerPolicyList)) {
                        for (RangerPolicy rangerPolicy : rangerPolicyList) {
                            if (rangerPolicy != null) {
                                Map<String, RangerPolicy.RangerPolicyResource> rangerPolicyResourceMap = rangerPolicy.getResources();
                                if (rangerPolicyResourceMap != null) {
                                    RangerPolicy.RangerPolicyResource rangerPolicyResource = null;
                                    if (rangerPolicyResourceMap.containsKey("path")) {
                                        rangerPolicyResource = rangerPolicyResourceMap.get("path");
                                    } else if (rangerPolicyResourceMap.containsKey("database")) {
                                        rangerPolicyResource = rangerPolicyResourceMap.get("database");
                                    }
                                    if (rangerPolicyResource != null) {
                                        if (CollectionUtils.isNotEmpty(rangerPolicyResource.getValues()) && rangerPolicyResource.getValues().size() > 1) {
                                            continue;
                                        }
                                    }
                                }
                                if (rangerPolicy.getId() != null) {
                                    if (!exportedPolicyNames.contains(rangerPolicy.getName())) {
                                        deletePolicy(rangerPolicy.getId());
                                        if (LOG.isDebugEnabled()) {
                                            LOG.debug("Policy " + rangerPolicy.getName() + " deleted successfully.");
                                        }
                                        totalDeletedPilicies = totalDeletedPilicies + 1;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
Also used : RangerPolicy(org.apache.ranger.plugin.model.RangerPolicy) RangerPolicyResource(org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource) VXString(org.apache.ranger.view.VXString) RangerPolicyList(org.apache.ranger.view.RangerPolicyList) RangerPolicyResource(org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource) HashSet(java.util.HashSet)

Example 62 with RangerPolicy

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

the class ServiceREST method createPolicy.

@POST
@Path("/policies")
@Produces({ "application/json", "application/xml" })
public RangerPolicy createPolicy(RangerPolicy policy, @Context HttpServletRequest request) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> ServiceREST.createPolicy(" + policy + ")");
    }
    RangerPolicy ret = null;
    RangerPerfTracer perf = null;
    try {
        if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
            perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.createPolicy(policyName=" + policy.getName() + ")");
        }
        if (request != null) {
            String serviceName = request.getParameter(PARAM_SERVICE_NAME);
            String policyName = request.getParameter(PARAM_POLICY_NAME);
            String updateIfExists = request.getParameter(PARAM_UPDATE_IF_EXISTS);
            if (serviceName == null && policyName == null && updateIfExists != null && updateIfExists.equalsIgnoreCase("true")) {
                serviceName = (String) request.getAttribute(PARAM_SERVICE_NAME);
                policyName = (String) request.getAttribute(PARAM_POLICY_NAME);
            }
            if (StringUtils.isNotEmpty(serviceName)) {
                policy.setService(serviceName);
            }
            if (StringUtils.isNotEmpty(policyName)) {
                policy.setName(StringUtils.trim(policyName));
            }
            if (updateIfExists != null && Boolean.valueOf(updateIfExists)) {
                RangerPolicy existingPolicy = null;
                try {
                    if (StringUtils.isNotEmpty(policy.getGuid())) {
                        existingPolicy = getPolicyByGuid(policy.getGuid());
                    }
                    if (existingPolicy == null && StringUtils.isNotEmpty(serviceName) && StringUtils.isNotEmpty(policyName)) {
                        existingPolicy = getPolicyByName(policy.getService(), policy.getName());
                    }
                    if (existingPolicy != null) {
                        policy.setId(existingPolicy.getId());
                        ret = updatePolicy(policy);
                    }
                } catch (Exception excp) {
                    LOG.info("ServiceREST.createPolicy(): Failed to find/update exising policy, will attempt to create the policy", excp);
                }
            }
        }
        if (ret == null) {
            // set name of policy if unspecified
            if (StringUtils.isBlank(policy.getName())) {
                // use of isBlank over isEmpty is deliberate as a blank string does not strike us as a particularly useful policy name!
                String guid = policy.getGuid();
                if (StringUtils.isBlank(guid)) {
                    // use of isBlank is deliberate. External parties could send the guid in, perhaps to sync between dev/test/prod instances?
                    guid = guidUtil.genGUID();
                    policy.setGuid(guid);
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("No GUID supplied on the policy!  Ok, setting GUID to [" + guid + "].");
                    }
                }
                String name = policy.getService() + "-" + guid;
                policy.setName(name);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Policy did not have its name set!  Ok, setting name to [" + name + "]");
                }
            }
            RangerPolicyValidator validator = validatorFactory.getPolicyValidator(svcStore);
            validator.validate(policy, Action.CREATE, bizUtil.isAdmin());
            ensureAdminAccess(policy);
            bizUtil.blockAuditorRoleUser();
            ret = svcStore.createPolicy(policy);
        }
    } catch (WebApplicationException excp) {
        throw excp;
    } catch (Throwable excp) {
        LOG.error("createPolicy(" + policy + ") failed", excp);
        throw restErrorUtil.createRESTException(excp.getMessage());
    } finally {
        RangerPerfTracer.log(perf);
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("<== ServiceREST.createPolicy(" + policy + "): " + ret);
    }
    return ret;
}
Also used : RangerPolicy(org.apache.ranger.plugin.model.RangerPolicy) WebApplicationException(javax.ws.rs.WebApplicationException) RangerPerfTracer(org.apache.ranger.plugin.util.RangerPerfTracer) VXString(org.apache.ranger.view.VXString) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException) JsonSyntaxException(com.google.gson.JsonSyntaxException) RangerPolicyValidator(org.apache.ranger.plugin.model.validation.RangerPolicyValidator) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Example 63 with RangerPolicy

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

the class ServiceREST method getPolicyFromEventTime.

@GET
@Path("/policies/eventTime")
@Produces({ "application/json", "application/xml" })
@PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.GET_POLICY_FROM_EVENT_TIME + "\")")
public RangerPolicy getPolicyFromEventTime(@Context HttpServletRequest request) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> ServiceREST.getPolicyFromEventTime()");
    }
    String eventTimeStr = request.getParameter("eventTime");
    String policyIdStr = request.getParameter("policyId");
    if (StringUtils.isEmpty(eventTimeStr) || StringUtils.isEmpty(policyIdStr)) {
        throw restErrorUtil.createRESTException("EventTime or policyId cannot be null or empty string.", MessageEnums.INVALID_INPUT_DATA);
    }
    Long policyId = Long.parseLong(policyIdStr);
    RangerPolicy policy = null;
    try {
        policy = svcStore.getPolicyFromEventTime(eventTimeStr, policyId);
        if (policy != null) {
            ensureAdminAndAuditAccess(policy);
        }
    } catch (WebApplicationException excp) {
        throw excp;
    } catch (Throwable excp) {
        LOG.error("getPolicy(" + policyId + ") failed", excp);
        throw restErrorUtil.createRESTException(excp.getMessage());
    }
    if (policy == null) {
        throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "Not found", true);
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("<== ServiceREST.getPolicy(" + policyId + "): " + policy);
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("<== ServiceREST.getPolicyFromEventTime()");
    }
    return policy;
}
Also used : RangerPolicy(org.apache.ranger.plugin.model.RangerPolicy) WebApplicationException(javax.ws.rs.WebApplicationException) VXString(org.apache.ranger.view.VXString) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Example 64 with RangerPolicy

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

the class ServiceREST method getPoliciesForResource.

@GET
@Path("/policies/{serviceDefName}/for-resource")
@Produces({ "application/json", "application/xml" })
public List<RangerPolicy> getPoliciesForResource(@PathParam("serviceDefName") String serviceDefName, @DefaultValue("") @QueryParam("serviceName") String serviceName, @Context HttpServletRequest request) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> ServiceREST.getPoliciesForResource(service-type=" + serviceDefName + ", service-name=" + serviceName + ")");
    }
    List<RangerPolicy> ret = new ArrayList<>();
    List<RangerService> services = new ArrayList<>();
    Map<String, Object> resource = new HashMap<>();
    String validationMessage = validateResourcePoliciesRequest(serviceDefName, serviceName, request, services, resource);
    if (StringUtils.isNotEmpty(validationMessage)) {
        LOG.error("Invalid request: [" + validationMessage + "]");
        throw restErrorUtil.createRESTException(validationMessage, MessageEnums.INVALID_INPUT_DATA);
    } else {
        RangerService service = services.get(0);
        if (LOG.isDebugEnabled()) {
            LOG.debug("getServicePolicies with service-name=" + service.getName());
        }
        RangerPolicyEngine engine = null;
        try {
            engine = getPolicySearchPolicyEngine(service.getName());
        } catch (Exception e) {
            LOG.error("Cannot initialize Policy-Engine", e);
            throw restErrorUtil.createRESTException("Cannot initialize Policy Engine", MessageEnums.ERROR_SYSTEM);
        }
        if (engine != null) {
            ret = engine.getMatchingPolicies(new RangerAccessResourceImpl(resource));
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("<== ServiceREST.getPoliciesForResource(service-type=" + serviceDefName + ", service-name=" + serviceName + ") : " + ret.toString());
    }
    return ret;
}
Also used : RangerPolicy(org.apache.ranger.plugin.model.RangerPolicy) RangerAccessResourceImpl(org.apache.ranger.plugin.policyengine.RangerAccessResourceImpl) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) RangerPolicyEngine(org.apache.ranger.plugin.policyengine.RangerPolicyEngine) RangerService(org.apache.ranger.plugin.model.RangerService) VXString(org.apache.ranger.view.VXString) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException) JsonSyntaxException(com.google.gson.JsonSyntaxException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 65 with RangerPolicy

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

the class ServiceREST method getPoliciesInCsv.

@GET
@Path("/policies/csv")
@Produces("text/csv")
public void getPoliciesInCsv(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> ServiceREST.getPoliciesInCsv()");
    }
    RangerPerfTracer perf = null;
    SearchFilter filter = searchUtil.getSearchFilter(request, policyService.sortFields);
    try {
        if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
            perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getPoliciesInCsv()");
        }
        List<RangerPolicy> policyLists = new ArrayList<RangerPolicy>();
        policyLists = getAllFilteredPolicyList(filter, request, policyLists);
        if (CollectionUtils.isNotEmpty(policyLists)) {
            for (RangerPolicy rangerPolicy : policyLists) {
                if (rangerPolicy != null) {
                    ensureAdminAndAuditAccess(rangerPolicy);
                }
            }
            bizUtil.blockAuditorRoleUser();
            svcStore.getPoliciesInCSV(policyLists, response);
        } else {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
            LOG.error("No policies found to download!");
        }
        RangerExportPolicyList rangerExportPolicyList = new RangerExportPolicyList();
        svcStore.putMetaDataInfo(rangerExportPolicyList);
        String metaDataInfo = new ObjectMapper().writeValueAsString(rangerExportPolicyList.getMetaDataInfo());
        List<XXTrxLog> trxLogList = new ArrayList<XXTrxLog>();
        XXTrxLog xxTrxLog = new XXTrxLog();
        xxTrxLog.setAction("EXPORT CSV");
        xxTrxLog.setObjectClassType(AppConstants.CLASS_TYPE_RANGER_POLICY);
        xxTrxLog.setPreviousValue(metaDataInfo);
        trxLogList.add(xxTrxLog);
        bizUtil.createTrxLog(trxLogList);
    } catch (WebApplicationException excp) {
        throw excp;
    } catch (Throwable excp) {
        LOG.error("Error while downloading policy report", excp);
        throw restErrorUtil.createRESTException(excp.getMessage());
    } finally {
        RangerPerfTracer.log(perf);
    }
}
Also used : RangerPolicy(org.apache.ranger.plugin.model.RangerPolicy) WebApplicationException(javax.ws.rs.WebApplicationException) RangerPerfTracer(org.apache.ranger.plugin.util.RangerPerfTracer) RangerExportPolicyList(org.apache.ranger.view.RangerExportPolicyList) ArrayList(java.util.ArrayList) SearchFilter(org.apache.ranger.plugin.util.SearchFilter) VXString(org.apache.ranger.view.VXString) XXTrxLog(org.apache.ranger.entity.XXTrxLog) ObjectMapper(org.codehaus.jackson.map.ObjectMapper) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

RangerPolicy (org.apache.ranger.plugin.model.RangerPolicy)196 ArrayList (java.util.ArrayList)78 Test (org.junit.Test)73 RangerService (org.apache.ranger.plugin.model.RangerService)52 VXString (org.apache.ranger.view.VXString)48 HashMap (java.util.HashMap)38 RangerPolicyItem (org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem)36 RangerPolicyResource (org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource)33 SearchFilter (org.apache.ranger.plugin.util.SearchFilter)30 WebApplicationException (javax.ws.rs.WebApplicationException)29 RangerServiceDef (org.apache.ranger.plugin.model.RangerServiceDef)27 RangerPolicyItemAccess (org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItemAccess)26 Path (javax.ws.rs.Path)23 Produces (javax.ws.rs.Produces)22 RangerPerfTracer (org.apache.ranger.plugin.util.RangerPerfTracer)20 Date (java.util.Date)19 IOException (java.io.IOException)18 XXService (org.apache.ranger.entity.XXService)18 ServicePolicies (org.apache.ranger.plugin.util.ServicePolicies)16 RangerPolicyList (org.apache.ranger.view.RangerPolicyList)15