Search in sources :

Example 1 with ResourceResult

use of com.sun.identity.policy.ResourceResult in project OpenAM by OpenRock.

the class ResourceResultCache method mergePolicyDecisions.

/**
     * Merges policy decisions applicable to a resource 
     * from a <code>ResourceResult</code> object.
     *
     * @param pd a collector for merged policy decision
     * @param resourceResult <code>ResourceResult</code> from which
     * to find applicable policy decisions
     * @param resourceName resource name for which to get policy decision
     * @param resourceComparator <code>ResourceName</code>, resource
     * comparison algorithm used to compare resources
     *
     * @param serviceName service name
     *
     * @return a flag indicating whether more <code>ResourceResult</code>
     * objects need to be visited to to compute the policy decision.
     * <code>true</code> is returned if no more <code>ResourceResult</code>
     * objects need to be visited
     * 
     *
     * a <code>ResourceResult</code> object.
     *
     * @throws PolicyException if can not get policy decision
     */
private boolean mergePolicyDecisions(PolicyDecision pd, ResourceResult resourceResult, String resourceName, ResourceName resourceComparator, String serviceName) throws PolicyException {
    boolean processed = false;
    if (debug.messageEnabled()) {
        debug.message("ResourceResultCache.mergePolicyDecisions():" + "resourceName=" + resourceName + ":resourceResultResourceName=" + resourceResult.getResourceName());
    }
    ResourceMatch result = resourceComparator.compare(resourceName, resourceResult.getResourceName(), //wild card compare
    true);
    if (result.equals(ResourceMatch.EXACT_MATCH)) {
        resetPolicyDecision(resourceResult.getPolicyDecision(), pd, serviceName);
        processed = true;
    } else if (result.equals(ResourceMatch.WILDCARD_MATCH)) {
        mergePolicyDecisions(resourceResult.getPolicyDecision(), pd, serviceName);
        if (pd.getTimeToLive() < System.currentTimeMillis()) {
            processed = true;
        }
        if (!processed) {
            Set resourceResults = resourceResult.getResourceResults();
            Iterator resultsIter = resourceResults.iterator();
            while (!processed && resultsIter.hasNext()) {
                ResourceResult subResult = (ResourceResult) resultsIter.next();
                processed = mergePolicyDecisions(pd, subResult, resourceName, resourceComparator, serviceName);
            }
        }
    } else if (result.equals(ResourceMatch.SUPER_RESOURCE_MATCH)) {
        Set resourceResults = resourceResult.getResourceResults();
        Iterator resultsIter = resourceResults.iterator();
        while (!processed && resultsIter.hasNext()) {
            ResourceResult subResult = (ResourceResult) resultsIter.next();
            processed = mergePolicyDecisions(pd, subResult, resourceName, resourceComparator, serviceName);
        }
    }
    // else NO_MATCH or SUBRESOURCE_MATCH nothing to do
    return processed;
}
Also used : ResourceResult(com.sun.identity.policy.ResourceResult) Set(java.util.Set) HashSet(java.util.HashSet) RequestSet(com.iplanet.services.comm.share.RequestSet) Iterator(java.util.Iterator) ResourceMatch(com.sun.identity.policy.ResourceMatch)

Example 2 with ResourceResult

use of com.sun.identity.policy.ResourceResult in project OpenAM by OpenRock.

the class ResourceResultCache method getRESTResultsFromServer.

private Set getRESTResultsFromServer(SSOToken appToken, String serviceName, SSOToken token, String resourceName, String scope, Set actionNames, Map env) throws InvalidAppSSOTokenException, SSOException, PolicyException {
    Set<ResourceResult> resourceResults = null;
    try {
        AMIdentity userIdentity = IdUtils.getIdentity(token);
        String restUrl = getRESTPolicyServiceURL(token, scope);
        String queryString = buildEntitlementRequestQueryString("/", serviceName, token, resourceName, actionNames, env);
        restUrl = restUrl + "?" + queryString;
        if (debug.messageEnabled()) {
            debug.message("ResourceResultCache.getRESTResultsFromServer():" + ":serviceName=" + serviceName + ":token=" + token.getPrincipal().getName() + ":resourceName=" + resourceName + ":scope=" + scope + ":actionNames=" + actionNames + ":env" + ":restUrl=" + restUrl + ":entering");
        }
        String jsonString = getResourceContent(appToken, token, restUrl);
        if (debug.messageEnabled()) {
            debug.message("ResourceResultCache.getRESTResultsFromServer():" + ":server response jsonString=" + jsonString);
        }
        resourceResults = jsonResourceContentToResourceResults(jsonString, serviceName);
    } catch (InvalidAppSSOTokenException e) {
        throw e;
    } catch (Exception e) {
        String[] args = { e.getMessage() };
        throw new PolicyEvaluationException(ResBundleUtils.rbName, "rest_policy_request_exception", args, e);
    }
    if (debug.messageEnabled()) {
        debug.message("ResourceResultCache.getRESTResultsFromServer():" + "returning");
    }
    return resourceResults;
}
Also used : ResourceResult(com.sun.identity.policy.ResourceResult) AMIdentity(com.sun.identity.idm.AMIdentity) PolicyEvaluationException(com.sun.identity.policy.remote.PolicyEvaluationException) JSONException(org.json.JSONException) PolicyException(com.sun.identity.policy.PolicyException) SendRequestException(com.iplanet.services.comm.client.SendRequestException) PolicyEvaluationException(com.sun.identity.policy.remote.PolicyEvaluationException) URLNotFoundException(com.iplanet.services.naming.URLNotFoundException) SSOException(com.iplanet.sso.SSOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) AlreadyRegisteredException(com.iplanet.services.comm.client.AlreadyRegisteredException) IOException(java.io.IOException) SessionException(com.iplanet.dpro.session.SessionException)

Example 3 with ResourceResult

use of com.sun.identity.policy.ResourceResult in project OpenAM by OpenRock.

the class ResourceResultCache method jsonEntitlementToResourceResult.

ResourceResult jsonEntitlementToResourceResult(JSONObject jsonEntitlement, String serviceName) throws JSONException {
    String resultResourceName = jsonEntitlement.optString(JSON_RESOURCE_NAME);
    Map<String, Set<String>> actionsValues = JSONUtils.getMapStringSetString(jsonEntitlement, JSON_ACTIONS_VALUES);
    Map<String, Set<String>> advices = JSONUtils.getMapStringSetString(jsonEntitlement, JSON_ADVICES);
    Map<String, Set<String>> attributes = JSONUtils.getMapStringSetString(jsonEntitlement, JSON_ATTRIBUTES);
    Set<String> actNames = (actionsValues != null) ? actionsValues.keySet() : null;
    PolicyDecision pd = new PolicyDecision();
    if (actNames != null) {
        for (String actName : actNames) {
            Set<String> actValues = actionsValues.get(actName);
            actValues = mapActionBooleanToString(serviceName, actName, actValues);
            ActionDecision ad = new ActionDecision(actName, actValues);
            ad.setAdvices(advices);
            pd.addActionDecision(ad);
        }
    }
    pd.setResponseDecisions(attributes);
    ResourceResult resourceResult = new ResourceResult(resultResourceName, pd);
    return resourceResult;
}
Also used : PolicyDecision(com.sun.identity.policy.PolicyDecision) ResourceResult(com.sun.identity.policy.ResourceResult) Set(java.util.Set) HashSet(java.util.HashSet) RequestSet(com.iplanet.services.comm.share.RequestSet) ActionDecision(com.sun.identity.policy.ActionDecision)

Example 4 with ResourceResult

use of com.sun.identity.policy.ResourceResult in project OpenAM by OpenRock.

the class PolicyResponse method parseXML.

/**
     * Returns <code>PolicyResponse</code> object constructed from XML.
     *
     * @param pNode the XML DOM node for the <code>PolicyResponse</code> object.
     * @return constructed <code>PolicyResponse</code> object.
     */
public static PolicyResponse parseXML(Node pNode) throws PolicyEvaluationException {
    PolicyResponse pres = new PolicyResponse();
    Node node = null;
    String attr = XMLUtils.getNodeAttributeValue(pNode, REQUEST_ID);
    if (attr == null) {
        debug.error("PolicyResponse: missing attribute " + REQUEST_ID);
        String[] objs = { REQUEST_ID };
        throw new PolicyEvaluationException(ResBundleUtils.rbName, "missing_attribute", objs, null);
    }
    pres.setRequestId(attr);
    String issueInst = XMLUtils.getNodeAttributeValue(pNode, ISSUE_INSTANT);
    if ((issueInst != null) && (issueInst.length() != 0)) {
        try {
            pres.setIssueInstant(Long.parseLong(issueInst));
        } catch (NumberFormatException nfe) {
            //This should never happen 
            if (debug.warningEnabled()) {
                debug.message("PolicyResponse: invald value for attribute:" + ISSUE_INSTANT + ":" + issueInst);
            }
        }
    } else {
        if (debug.messageEnabled()) {
            debug.message("PolicyResponse: missing attribute: " + ISSUE_INSTANT);
        }
    }
    Set nodeSet = XMLUtils.getChildNodes(pNode, RESOURCE_RESULT);
    if ((nodeSet != null) && (!nodeSet.isEmpty())) {
        Set resResults = new HashSet();
        Iterator nodes = nodeSet.iterator();
        while (nodes.hasNext()) {
            node = (Node) nodes.next();
            ResourceResult rRes = null;
            try {
                rRes = ResourceResult.parseResourceResult(node);
            } catch (Exception e) {
                debug.error("PolicyResponse: XML parsing error");
                throw new PolicyEvaluationException(ResBundleUtils.rbName, "xml_parsing_error", null, e);
            }
            resResults.add(rRes);
        }
        pres.setResourceResults(resResults);
        pres.setMethodID(POLICY_RESPONSE_RESOURCE_RESULT);
        return pres;
    }
    node = XMLUtils.getChildNode(pNode, ADD_LISTENER_RESPONSE);
    if (node != null) {
        pres.setMethodID(POLICY_ADD_LISTENER_RESPONSE);
        return pres;
    }
    node = XMLUtils.getChildNode(pNode, REMOVE_LISTENER_RESPONSE);
    if (node != null) {
        pres.setMethodID(POLICY_REMOVE_LISTENER_RESPONSE);
        return pres;
    }
    node = XMLUtils.getChildNode(pNode, ADVICES_HANDLEABLE_BY_AM_RESPONSE);
    if (node != null) {
        pres.setAdvicesHandleableByAMResponse(AdvicesHandleableByAMResponse.parseXML(node));
        pres.setMethodID(POLICY_ADVICES_HANDLEABLE_BY_AM_RESPONSE);
        return pres;
    }
    node = XMLUtils.getChildNode(pNode, EXCEPTION_RESPONSE);
    if (node != null) {
        String eMsg = XMLUtils.getValueOfValueNode(node);
        pres.setExceptionMsg(eMsg);
        pres.setMethodID(POLICY_EXCEPTION);
        return pres;
    }
    /* We reach here, there is no valid method name specified in
           the xml docuemnt. Throw exception.
         */
    debug.error("PolicyResponse: invalid method specified");
    throw new PolicyEvaluationException(ResBundleUtils.rbName, "invalid_policy_response_method", null, null);
}
Also used : ResourceResult(com.sun.identity.policy.ResourceResult) HashSet(java.util.HashSet) Set(java.util.Set) Node(org.w3c.dom.Node) Iterator(java.util.Iterator) HashSet(java.util.HashSet)

Example 5 with ResourceResult

use of com.sun.identity.policy.ResourceResult in project OpenAM by OpenRock.

the class PolicyRequestHandler method processPolicyRequest.

/**
     * Processes a policy request and return a policy response.
     *
     * @param req a policy request
     * @return its corresponding policy response
     */
private PolicyResponse processPolicyRequest(PolicyRequest req, PLLAuditor auditor) throws PolicyEvaluationException {
    if (debug.messageEnabled()) {
        debug.message("PolicyRequestHandler.processPolicyRequest(): " + " req received:\n" + req.toXMLString());
    }
    PolicyResponse policyRes = new PolicyResponse();
    String requestId = req.getRequestId();
    policyRes.setRequestId(requestId);
    String appSSOTokenIDStr = req.getAppSSOToken();
    SSOToken appToken = null;
    Map<String, Set<String>> appAttributes;
    try {
        appToken = getSSOToken(appSSOTokenIDStr, null);
        appAttributes = IdUtils.getIdentity(appToken).getAttributes();
    } catch (IdRepoException | SSOException | PolicyException pe) {
        if (debug.warningEnabled()) {
            debug.warning("PolicyRequestHandler: Invalid app sso token, " + appSSOTokenIDStr);
        }
        throw new PolicyEvaluationException(PolicyResponse.APP_SSO_TOKEN_INVALID, requestId);
    }
    // set the app token into the ThreadLocal
    AppTokenHandler.set(appToken);
    auditor.setMethod(req.getMethodName());
    auditor.setSsoToken(appToken);
    auditor.setRealm(getFirstItem(appAttributes.get(EVALUATION_REALM), NO_REALM));
    auditor.auditAccessAttempt();
    if (req.getMethodID() == PolicyRequest.POLICY_REQUEST_ADD_POLICY_LISTENER) {
        PolicyListenerRequest plReq = req.getPolicyListenerRequest();
        boolean addListener = addPolicyListener(appToken, plReq, appAttributes);
        if (addListener) {
            policyRes.setMethodID(PolicyResponse.POLICY_ADD_LISTENER_RESPONSE);
            auditor.auditAccessSuccess();
        } else {
            String[] objs = { plReq.getNotificationURL() };
            String message = ResBundleUtils.getString("failed.add.policy.listener", objs);
            policyRes.setExceptionMsg(message);
            policyRes.setMethodID(PolicyResponse.POLICY_EXCEPTION);
            auditor.auditAccessFailure(message);
        }
        return policyRes;
    }
    if (req.getMethodID() == PolicyRequest.POLICY_REQUEST_REMOVE_POLICY_LISTENER) {
        RemoveListenerRequest rmReq = req.getRemoveListenerRequest();
        boolean removeListener = removePolicyListener(appToken, rmReq, appAttributes);
        if (removeListener) {
            policyRes.setMethodID(PolicyResponse.POLICY_REMOVE_LISTENER_RESPONSE);
            auditor.auditAccessSuccess();
        } else {
            String[] objs = { rmReq.getNotificationURL() };
            String message = ResBundleUtils.getString("failed.remove.policy.listener", objs);
            policyRes.setExceptionMsg(message);
            policyRes.setMethodID(PolicyResponse.POLICY_EXCEPTION);
            auditor.auditAccessFailure(message);
        }
        return policyRes;
    }
    if (req.getMethodID() == PolicyRequest.POLICY_REQUEST_ADVICES_HANDLEABLE_BY_AM_REQUEST) {
        if (debug.messageEnabled()) {
            debug.message("PolicyRequestHandler: request to get  " + " advicesHandleableByAM");
        }
        try {
            Set advices = PolicyConfig.getAdvicesHandleableByAM();
            policyRes.setAdvicesHandleableByAMResponse(new AdvicesHandleableByAMResponse(advices));
            policyRes.setMethodID(PolicyResponse.POLICY_ADVICES_HANDLEABLE_BY_AM_RESPONSE);
            auditor.auditAccessSuccess();
        } catch (PolicyException pe) {
            if (debug.warningEnabled()) {
                debug.warning("PolicyRequestHandler: could not get " + " advicesHandleableByAM", pe);
            }
            throw new PolicyEvaluationException(ResBundleUtils.rbName, "could_not_get_advices_handleable_by_am", null, pe, requestId);
        }
        if (debug.messageEnabled()) {
            debug.message("PolicyRequestHandler: returning  " + " advicesHandleableByAM policy response");
        }
        return policyRes;
    }
    if (req.getMethodID() == PolicyRequest.POLICY_REQUEST_GET_RESOURCE_RESULTS) {
        ResourceResultRequest resourceResultReq = req.getResourceResultRequest();
        // Get the user's SSO token id string from the request
        String userSSOTokenIDStr = resourceResultReq.getUserSSOToken();
        SSOToken userToken = null;
        if ((userSSOTokenIDStr != null) && !userSSOTokenIDStr.equals(PolicyUtils.EMPTY_STRING) && !userSSOTokenIDStr.equals(PolicyUtils.NULL_STRING)) {
            try {
                userToken = getSSOToken(userSSOTokenIDStr, appToken);
            } catch (PolicyException pe) {
                if (debug.warningEnabled()) {
                    debug.warning("PolicyRequestHandler: Invalid user sso token, " + userSSOTokenIDStr, pe);
                }
                throw new PolicyEvaluationException(ResBundleUtils.rbName, "user_sso_token_invalid", null, null, requestId);
            }
        }
        Set resourceResults = new HashSet();
        ResourceResults resourceRst = null;
        // check if the request contains user response attributes
        Set respAttrs = resourceResultReq.getResponseAttributes();
        if (debug.messageEnabled()) {
            debug.message("PolicyRequestHandler.processPolicyRequest(): " + "respAttrs=\n" + respAttrs);
        }
        Map respDecisions = null;
        if ((respAttrs != null) && (userToken != null)) {
            // get the response decisions wrt the attributes  
            respDecisions = getResponseDecisions(userToken, respAttrs);
        }
        // Get the service name and resource name of the request
        String serviceName = resourceResultReq.getServiceName();
        String resourceName = resourceResultReq.getResourceName();
        // Get the resource scope of the request
        String resourceScope = resourceResultReq.getResourceScope();
        if ((resourceScope != null) && resourceScope.equals(ResourceResultRequest.RESPONSE_ATTRIBUTES_ONLY)) {
            // need not to evaluate policies, do attributes only
            ResourceResult resResult = new ResourceResult(resourceName, new PolicyDecision());
            Set results = new HashSet();
            results.add(resResult);
            resourceRst = new ResourceResults(results);
        } else {
            // Get the environment parameters of the request
            Map envParameters = resourceResultReq.getEnvParms();
            try {
                convertEnvParams(envParameters);
            } catch (PolicyException pe) {
                debug.error("PolicyRequestHandler: Invalid env parameters", pe);
                throw new PolicyEvaluationException(ResBundleUtils.rbName, "invalid_env_parameters", null, pe, requestId);
            }
            PolicyEvaluator policyEvaluator = null;
            try {
                // Get an instance of the policy evaluator
                policyEvaluator = getPolicyEvaluator(appToken, serviceName, appAttributes);
                // Get the resource result from the policy evaluator
                resourceRst = new ResourceResults(policyEvaluator.getResourceResults(userToken, resourceName, resourceScope, envParameters));
                if (debug.messageEnabled()) {
                    debug.message("PolicyRequestHandler.processPolicyRequest():" + " resource result:\n" + resourceRst.toXML());
                }
            } catch (Exception se) {
                debug.error("PolicyRequestHandler: Evaluation error", se);
                throw new PolicyEvaluationException(ResBundleUtils.rbName, "evaluation_error", null, se, requestId);
            }
        }
        resourceRst.setResponseDecisions(respDecisions);
        resourceResults.addAll(resourceRst.getResourceResults());
        policyRes.setResourceResults(resourceResults);
        policyRes.setMethodID(PolicyResponse.POLICY_RESPONSE_RESOURCE_RESULT);
        auditor.auditAccessSuccess();
        return policyRes;
    }
    debug.error("PolicyRequestHandler: Invalid policy request format");
    throw new PolicyEvaluationException(ResBundleUtils.rbName, "invalid_policy_request_format", null, null);
}
Also used : PolicyDecision(com.sun.identity.policy.PolicyDecision) SSOToken(com.iplanet.sso.SSOToken) ResponseSet(com.iplanet.services.comm.share.ResponseSet) HashSet(java.util.HashSet) Set(java.util.Set) IdRepoException(com.sun.identity.idm.IdRepoException) SSOException(com.iplanet.sso.SSOException) IdRepoException(com.sun.identity.idm.IdRepoException) EntitlementException(com.sun.identity.entitlement.EntitlementException) PolicyException(com.sun.identity.policy.PolicyException) SMSException(com.sun.identity.sm.SMSException) SSOException(com.iplanet.sso.SSOException) ResourceResult(com.sun.identity.policy.ResourceResult) PolicyEvaluator(com.sun.identity.policy.PolicyEvaluator) PolicyException(com.sun.identity.policy.PolicyException) HashMap(java.util.HashMap) Map(java.util.Map) ResourceResults(com.sun.identity.policy.ResourceResults) HashSet(java.util.HashSet)

Aggregations

ResourceResult (com.sun.identity.policy.ResourceResult)10 PolicyDecision (com.sun.identity.policy.PolicyDecision)6 HashSet (java.util.HashSet)5 Iterator (java.util.Iterator)4 Set (java.util.Set)4 PolicyEvaluator (com.sun.identity.policy.PolicyEvaluator)3 RequestSet (com.iplanet.services.comm.share.RequestSet)2 SSOException (com.iplanet.sso.SSOException)2 ActionDecision (com.sun.identity.policy.ActionDecision)2 PolicyException (com.sun.identity.policy.PolicyException)2 PolicyEvaluationException (com.sun.identity.policy.remote.PolicyEvaluationException)2 JSONException (org.json.JSONException)2 SessionException (com.iplanet.dpro.session.SessionException)1 AlreadyRegisteredException (com.iplanet.services.comm.client.AlreadyRegisteredException)1 SendRequestException (com.iplanet.services.comm.client.SendRequestException)1 ResponseSet (com.iplanet.services.comm.share.ResponseSet)1 URLNotFoundException (com.iplanet.services.naming.URLNotFoundException)1 SSOToken (com.iplanet.sso.SSOToken)1 EntitlementException (com.sun.identity.entitlement.EntitlementException)1 AMIdentity (com.sun.identity.idm.AMIdentity)1