Search in sources :

Example 6 with RESTResponse

use of org.apache.ranger.admin.client.datatype.RESTResponse in project ranger by apache.

the class RangerAdminRESTClient method getServiceTagsIfUpdated.

@Override
public ServiceTags getServiceTagsIfUpdated(final long lastKnownVersion, final long lastActivationTimeInMillis) throws Exception {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> RangerAdminRESTClient.getServiceTagsIfUpdated(" + lastKnownVersion + ", " + lastActivationTimeInMillis + "): ");
    }
    ServiceTags ret = null;
    ClientResponse response = null;
    WebResource webResource = null;
    UserGroupInformation user = MiscUtil.getUGILoginUser();
    boolean isSecureMode = user != null && UserGroupInformation.isSecurityEnabled();
    if (isSecureMode) {
        PrivilegedAction<ClientResponse> action = new PrivilegedAction<ClientResponse>() {

            public ClientResponse run() {
                WebResource secureWebResource = createWebResource(RangerRESTUtils.REST_URL_GET_SECURE_SERVICE_TAGS_IF_UPDATED + serviceName).queryParam(RangerRESTUtils.LAST_KNOWN_TAG_VERSION_PARAM, Long.toString(lastKnownVersion)).queryParam(RangerRESTUtils.REST_PARAM_LAST_ACTIVATION_TIME, Long.toString(lastActivationTimeInMillis)).queryParam(RangerRESTUtils.REST_PARAM_PLUGIN_ID, pluginId);
                return secureWebResource.accept(RangerRESTUtils.REST_MIME_TYPE_JSON).get(ClientResponse.class);
            }
        };
        if (LOG.isDebugEnabled()) {
            LOG.debug("getServiceTagsIfUpdated as user " + user);
        }
        response = user.doAs(action);
    } else {
        webResource = createWebResource(RangerRESTUtils.REST_URL_GET_SERVICE_TAGS_IF_UPDATED + serviceName).queryParam(RangerRESTUtils.LAST_KNOWN_TAG_VERSION_PARAM, Long.toString(lastKnownVersion)).queryParam(RangerRESTUtils.REST_PARAM_LAST_ACTIVATION_TIME, Long.toString(lastActivationTimeInMillis)).queryParam(RangerRESTUtils.REST_PARAM_PLUGIN_ID, pluginId);
        response = webResource.accept(RangerRESTUtils.REST_MIME_TYPE_JSON).get(ClientResponse.class);
    }
    if (response == null || response.getStatus() == HttpServletResponse.SC_NOT_MODIFIED) {
        if (response == null) {
            LOG.error("Error getting tags; Received NULL response!!. secureMode=" + isSecureMode + ", user=" + user + ", serviceName=" + serviceName);
        } else {
            RESTResponse resp = RESTResponse.fromClientResponse(response);
            if (LOG.isDebugEnabled()) {
                LOG.debug("No change in tags. secureMode=" + isSecureMode + ", user=" + user + ", response=" + resp + ", serviceName=" + serviceName + ", " + "lastKnownVersion=" + lastKnownVersion + ", " + "lastActivationTimeInMillis=" + lastActivationTimeInMillis);
            }
        }
        ret = null;
    } else if (response.getStatus() == HttpServletResponse.SC_OK) {
        ret = response.getEntity(ServiceTags.class);
    } else if (response.getStatus() == HttpServletResponse.SC_NOT_FOUND) {
        LOG.error("Error getting tags; service not found. secureMode=" + isSecureMode + ", user=" + user + ", response=" + response.getStatus() + ", serviceName=" + serviceName + ", " + "lastKnownVersion=" + lastKnownVersion + ", " + "lastActivationTimeInMillis=" + lastActivationTimeInMillis);
        String exceptionMsg = response.hasEntity() ? response.getEntity(String.class) : null;
        RangerServiceNotFoundException.throwExceptionIfServiceNotFound(serviceName, exceptionMsg);
        LOG.warn("Received 404 error code with body:[" + exceptionMsg + "], Ignoring");
    } else {
        RESTResponse resp = RESTResponse.fromClientResponse(response);
        LOG.warn("Error getting tags. secureMode=" + isSecureMode + ", user=" + user + ", response=" + resp + ", serviceName=" + serviceName);
        ret = null;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("<== RangerAdminRESTClient.getServiceTagsIfUpdated(" + lastKnownVersion + ", " + lastActivationTimeInMillis + "): ");
    }
    return ret;
}
Also used : ClientResponse(com.sun.jersey.api.client.ClientResponse) PrivilegedAction(java.security.PrivilegedAction) RESTResponse(org.apache.ranger.admin.client.datatype.RESTResponse) ServiceTags(org.apache.ranger.plugin.util.ServiceTags) WebResource(com.sun.jersey.api.client.WebResource) UserGroupInformation(org.apache.hadoop.security.UserGroupInformation)

Example 7 with RESTResponse

use of org.apache.ranger.admin.client.datatype.RESTResponse in project ranger by apache.

the class AssetREST method grantPermission.

@POST
@Path("/resources/grant")
@Produces({ "application/xml", "application/json" })
public VXPolicy grantPermission(@Context HttpServletRequest request, VXPolicy vXPolicy) {
    RESTResponse ret = null;
    if (logger.isDebugEnabled()) {
        logger.debug("==> AssetREST.grantPermission(" + vXPolicy + ")");
    }
    if (vXPolicy != null) {
        String serviceName = vXPolicy.getRepositoryName();
        GrantRevokeRequest grantRevokeRequest = serviceUtil.toGrantRevokeRequest(vXPolicy);
        try {
            ret = serviceREST.grantAccess(serviceName, grantRevokeRequest, request);
        } catch (WebApplicationException excp) {
            throw excp;
        } catch (Throwable e) {
            logger.error(HttpServletResponse.SC_BAD_REQUEST + "Grant Access Failed for the request " + vXPolicy, e);
            throw restErrorUtil.createRESTException("Grant Access Failed for the request: " + vXPolicy + ". " + e.getMessage());
        }
    } else {
        logger.error(HttpServletResponse.SC_BAD_REQUEST + "Bad Request parameter");
        throw restErrorUtil.createRESTException("Bad Request parameter");
    }
    if (logger.isDebugEnabled()) {
        logger.debug("<== AssetREST.grantPermission(" + ret + ")");
    }
    // TO DO Current Grant REST doesn't return a policy so returning a null value. Has to be replace with VXpolicy.
    return vXPolicy;
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) RESTResponse(org.apache.ranger.admin.client.datatype.RESTResponse) GrantRevokeRequest(org.apache.ranger.plugin.util.GrantRevokeRequest) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Example 8 with RESTResponse

use of org.apache.ranger.admin.client.datatype.RESTResponse in project ranger by apache.

the class ServiceREST method grantAccess.

@POST
@Path("/services/grant/{serviceName}")
@Produces({ "application/json", "application/xml" })
public RESTResponse grantAccess(@PathParam("serviceName") String serviceName, GrantRevokeRequest grantRequest, @Context HttpServletRequest request) throws Exception {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> ServiceREST.grantAccess(" + serviceName + ", " + grantRequest + ")");
    }
    RESTResponse ret = new RESTResponse();
    RangerPerfTracer perf = null;
    if (grantRequest != null) {
        if (serviceUtil.isValidateHttpsAuthentication(serviceName, request)) {
            try {
                if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
                    perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.grantAccess(serviceName=" + serviceName + ")");
                }
                validateGrantRevokeRequest(grantRequest);
                String userName = grantRequest.getGrantor();
                Set<String> userGroups = CollectionUtils.isNotEmpty(grantRequest.getGrantorGroups()) ? grantRequest.getGrantorGroups() : userMgr.getGroupsForUser(userName);
                RangerAccessResource resource = new RangerAccessResourceImpl(StringUtil.toStringObjectMap(grantRequest.getResource()));
                VXUser vxUser = xUserService.getXUserByUserName(userName);
                if (vxUser.getUserRoleList().contains(RangerConstants.ROLE_ADMIN_AUDITOR) || vxUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR)) {
                    VXResponse vXResponse = new VXResponse();
                    vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
                    vXResponse.setMsgDesc("Operation" + " denied. LoggedInUser=" + vxUser.getId() + " ,isn't permitted to perform the action.");
                    throw restErrorUtil.generateRESTException(vXResponse);
                }
                boolean isAdmin = hasAdminAccess(serviceName, userName, userGroups, resource);
                if (!isAdmin) {
                    throw restErrorUtil.createGrantRevokeRESTException("User doesn't have necessary permission to grant access");
                }
                RangerPolicy policy = getExactMatchPolicyForResource(serviceName, resource, userName);
                if (policy != null) {
                    boolean policyUpdated = false;
                    policyUpdated = ServiceRESTUtil.processGrantRequest(policy, grantRequest);
                    if (policyUpdated) {
                        svcStore.updatePolicy(policy);
                    } else {
                        LOG.error("processGrantRequest processing failed");
                        throw new Exception("processGrantRequest 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());
                    for (String accessType : grantRequest.getAccessTypes()) {
                        policyItem.getAccesses().add(new RangerPolicyItemAccess(accessType, Boolean.TRUE));
                    }
                    policy.getPolicyItems().add(policyItem);
                    svcStore.createPolicy(policy);
                }
            } catch (WebApplicationException excp) {
                throw excp;
            } catch (Throwable excp) {
                LOG.error("grantAccess(" + serviceName + ", " + grantRequest + ") failed", excp);
                throw restErrorUtil.createRESTException(excp.getMessage());
            } finally {
                RangerPerfTracer.log(perf);
            }
            ret.setStatusCode(RESTResponse.STATUS_SUCCESS);
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("<== ServiceREST.grantAccess(" + serviceName + ", " + grantRequest + "): " + ret);
    }
    return ret;
}
Also used : VXResponse(org.apache.ranger.view.VXResponse) 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) VXUser(org.apache.ranger.view.VXUser) 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) RangerAccessResource(org.apache.ranger.plugin.policyengine.RangerAccessResource) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Example 9 with RESTResponse

use of org.apache.ranger.admin.client.datatype.RESTResponse in project ranger by apache.

the class RESTErrorUtil method createGrantRevokeRESTException.

public WebApplicationException createGrantRevokeRESTException(String logMessage) {
    RESTResponse resp = new RESTResponse();
    resp.setMsgDesc(logMessage);
    Response errorResponse = Response.status(javax.servlet.http.HttpServletResponse.SC_FORBIDDEN).entity(resp).build();
    WebApplicationException restException = new WebApplicationException(errorResponse);
    restException.fillInStackTrace();
    UserSessionBase userSession = ContextUtil.getCurrentUserSession();
    String loginId = null;
    if (userSession != null) {
        loginId = userSession.getLoginId();
    }
    logger.info("Request failed. loginId=" + loginId + ", logMessage=" + logMessage, restException);
    return restException;
}
Also used : Response(javax.ws.rs.core.Response) RESTResponse(org.apache.ranger.admin.client.datatype.RESTResponse) VXResponse(org.apache.ranger.view.VXResponse) WebApplicationException(javax.ws.rs.WebApplicationException) RESTResponse(org.apache.ranger.admin.client.datatype.RESTResponse)

Example 10 with RESTResponse

use of org.apache.ranger.admin.client.datatype.RESTResponse in project ranger by apache.

the class AssetREST method revokePermission.

@POST
@Path("/resources/revoke")
@Produces({ "application/xml", "application/json" })
public VXPolicy revokePermission(@Context HttpServletRequest request, VXPolicy vXPolicy) {
    RESTResponse ret = null;
    if (logger.isDebugEnabled()) {
        logger.debug("==> AssetREST.revokePermission(" + vXPolicy + ")");
    }
    if (vXPolicy != null) {
        String serviceName = vXPolicy.getRepositoryName();
        GrantRevokeRequest grantRevokeRequest = serviceUtil.toGrantRevokeRequest(vXPolicy);
        try {
            ret = serviceREST.revokeAccess(serviceName, grantRevokeRequest, request);
        } catch (WebApplicationException excp) {
            throw excp;
        } catch (Throwable e) {
            logger.error(HttpServletResponse.SC_BAD_REQUEST + "Revoke Access Failed for the request " + vXPolicy, e);
            throw restErrorUtil.createRESTException("Revoke Access Failed for the request: " + vXPolicy + ". " + e.getMessage());
        }
    } else {
        logger.error(HttpServletResponse.SC_BAD_REQUEST + "Bad Request parameter");
        throw restErrorUtil.createRESTException("Bad Request parameter");
    }
    if (logger.isDebugEnabled()) {
        logger.debug("<== AssetREST.revokePermission(" + ret + ")");
    }
    return vXPolicy;
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) RESTResponse(org.apache.ranger.admin.client.datatype.RESTResponse) GrantRevokeRequest(org.apache.ranger.plugin.util.GrantRevokeRequest) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Aggregations

RESTResponse (org.apache.ranger.admin.client.datatype.RESTResponse)17 WebApplicationException (javax.ws.rs.WebApplicationException)9 ClientResponse (com.sun.jersey.api.client.ClientResponse)6 WebResource (com.sun.jersey.api.client.WebResource)6 POST (javax.ws.rs.POST)6 Path (javax.ws.rs.Path)6 Produces (javax.ws.rs.Produces)6 RangerPolicy (org.apache.ranger.plugin.model.RangerPolicy)6 GrantRevokeRequest (org.apache.ranger.plugin.util.GrantRevokeRequest)6 VXString (org.apache.ranger.view.VXString)6 IOException (java.io.IOException)5 PrivilegedAction (java.security.PrivilegedAction)5 UserGroupInformation (org.apache.hadoop.security.UserGroupInformation)5 JsonSyntaxException (com.google.gson.JsonSyntaxException)4 RangerService (org.apache.ranger.plugin.model.RangerService)4 RangerAccessResource (org.apache.ranger.plugin.policyengine.RangerAccessResource)4 RangerAccessResourceImpl (org.apache.ranger.plugin.policyengine.RangerAccessResourceImpl)4 RangerPerfTracer (org.apache.ranger.plugin.util.RangerPerfTracer)4 Test (org.junit.Test)4 AccessControlException (org.apache.hadoop.security.AccessControlException)3