org.wso2.balana.ctx.AbstractResult Java Examples

The following examples show how to use org.wso2.balana.ctx.AbstractResult. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractPolicy.java    From balana with Apache License 2.0 6 votes vote down vote up
/**
 * helper method to evaluate the obligations and advice expressions
 *
 * @param evaluationCtx context of a single policy evaluation
 * @param effect policy effect
 * @param result result of combining algorithm
 */
private void processObligationAndAdvices(EvaluationCtx evaluationCtx, int effect, AbstractResult result){

    if(obligationExpressions != null && obligationExpressions.size() > 0){
        Set<ObligationResult>  results = new HashSet<ObligationResult>();
        for(AbstractObligation obligationExpression : obligationExpressions){
            if(obligationExpression.getFulfillOn() == effect) {
                results.add(obligationExpression.evaluate(evaluationCtx));
            }
        }
        result.getObligations().addAll(results);
    }

    if(adviceExpressions != null && adviceExpressions.size() > 0){
        Set<Advice>  advices = new HashSet<Advice>();
        for(AdviceExpression adviceExpression : adviceExpressions){
            if(adviceExpression.getAppliesTo() == effect) {
                advices.add(adviceExpression.evaluate(evaluationCtx));
            }
        }
        result.getAdvices().addAll(advices);
    }
}
 
Example #2
Source File: AbstractPolicy.java    From balana with Apache License 2.0 6 votes vote down vote up
/**
 * Tries to evaluate the policy by calling the combining algorithm on the given policies or
 * rules. The <code>match</code> method must always be called first, and must always return
 * MATCH, before this method is called.
 *
 * @param context the representation of the request
 *
 * @return the result of evaluation
 */
public AbstractResult evaluate(EvaluationCtx context) {
    
    // evaluate
    AbstractResult result = combiningAlg.combine(context, parameters, childElements);

    // if we have no obligation expressions or advice expressions, we're done
    if (obligationExpressions.size() < 1 && adviceExpressions.size() < 1){
        return result;
    }

    // if we have obligations,
    // now, see if we should add any obligations to the set
    int effect = result.getDecision();

    if ((effect == Result.DECISION_INDETERMINATE) || (effect == Result.DECISION_NOT_APPLICABLE)) {
        // we didn't permit/deny, so we never return obligations
        return result;
    }
    
    // if any obligations or advices are defined, evaluates them and return
    processObligationAndAdvices(context, effect, result);
    return result;

}
 
Example #3
Source File: FirstApplicableRuleAlg.java    From balana with Apache License 2.0 6 votes vote down vote up
/**
 * Applies the combining rule to the set of rules based on the evaluation context.
 * 
 * @param context the context from the request
 * @param parameters a (possibly empty) non-null <code>List</code> of
 *            <code>CombinerParameter<code>s
 * @param ruleElements the rules to combine
 * 
 * @return the result of running the combining algorithm
 */
public AbstractResult combine(EvaluationCtx context, List parameters, List ruleElements) {
    Iterator it = ruleElements.iterator();
    while (it.hasNext()) {
        Rule rule = ((RuleCombinerElement) (it.next())).getRule();
        AbstractResult result = rule.evaluate(context);
        int value = result.getDecision();

        // in the case of PERMIT, DENY, or INDETERMINATE, we always
        // just return that result, so only on a rule that doesn't
        // apply do we keep going...
        if (value != Result.DECISION_NOT_APPLICABLE) {
            return result;
        }
    }

    // if we got here, then none of the rules applied
    return ResultFactory.getFactory().getResult(Result.DECISION_NOT_APPLICABLE, context);
}
 
Example #4
Source File: PolicySearch.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Helper method to get XACML decision
 *
 * @param requestAttributes XACML request attributes
 * @return whether permit or deny
 */
private boolean getResponse(List<AttributeDTO> requestAttributes) {

    ResponseCtx responseCtx;
    AbstractRequestCtx requestCtx = EntitlementUtil.createRequestContext(requestAttributes);

    responseCtx = EntitlementEngine.getInstance().evaluateByContext(requestCtx);

    if (responseCtx != null) {
        Set<AbstractResult> results = responseCtx.getResults();
        for (AbstractResult result : results) {
            if (result.getDecision() == AbstractResult.DECISION_PERMIT) {
                return true;
            }
        }
    }

    return false;
}
 
Example #5
Source File: PolicySearch.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Helper method to get XACML decision
 *
 * @param requestAttributes XACML request attributes
 * @return whether permit or deny
 */
private boolean getResponse(List<AttributeDTO> requestAttributes) {

    ResponseCtx responseCtx;
    AbstractRequestCtx requestCtx = EntitlementUtil.createRequestContext(requestAttributes);

    responseCtx = EntitlementEngine.getInstance().evaluateByContext(requestCtx);

    if (responseCtx != null) {
        Set<AbstractResult> results = responseCtx.getResults();
        for (AbstractResult result : results) {
            if (result.getDecision() == AbstractResult.DECISION_PERMIT) {
                return true;
            }
        }
    }

    return false;
}
 
Example #6
Source File: HighestEffectRuleAlg.java    From balana with Apache License 2.0 6 votes vote down vote up
@Override
public AbstractResult combine(EvaluationCtx context, List parameters, List ruleElements) {

    int noOfDenyRules = 0;
    int noOfPermitRules = 0;

    for (Object ruleElement : ruleElements) {
        
        Rule rule = ((RuleCombinerElement) (ruleElement)).getRule();
        AbstractResult result = rule.evaluate(context);

        int value = result.getDecision();
        if (value == Result.DECISION_DENY) {
            noOfDenyRules++;
        } else if (value == Result.DECISION_PERMIT) {
            noOfPermitRules++;
        }
    }

    if(noOfPermitRules > noOfDenyRules){
        return ResultFactory.getFactory().getResult(Result.DECISION_PERMIT, context);            
    } else {
        return ResultFactory.getFactory().getResult(Result.DECISION_DENY, context);     
    }
}
 
Example #7
Source File: DenyUnlessPermitRuleAlg.java    From balana with Apache License 2.0 6 votes vote down vote up
@Override
public AbstractResult combine(EvaluationCtx context, List parameters, List ruleElements) {

    List<ObligationResult> denyObligations = new ArrayList<ObligationResult>();
    List<Advice> denyAdvices = new ArrayList<Advice>();
    
    for (Object ruleElement : ruleElements) {
        Rule rule = ((RuleCombinerElement) (ruleElement)).getRule();
        AbstractResult result = rule.evaluate(context);
        int value = result.getDecision();

        // if there was a value of PERMIT, then regardless of what else
        // we've seen, we always return PERMIT
        if (value == AbstractResult.DECISION_PERMIT) {
            return result;
        } else if(value == AbstractResult.DECISION_DENY){
            denyObligations.addAll(result.getObligations());
            denyAdvices.addAll(result.getAdvices());
        }
    }

    // if there is not any value of PERMIT. The return DENY
    return ResultFactory.getFactory().getResult(AbstractResult.DECISION_DENY, denyObligations,
                                                                        denyAdvices, context);
}
 
Example #8
Source File: PolicyReference.java    From balana with Apache License 2.0 6 votes vote down vote up
/**
     * Tries to evaluate the policy by calling the combining algorithm on the given policies or
     * rules. The <code>match</code> method must always be called first, and must always return
     * MATCH, before this method is called.
     * 
     * @param context the representation of the request
     * 
     * @return the result of evaluation
     */
    public AbstractResult evaluate(EvaluationCtx context) {
        // if there is no finder, then we return NotApplicable
        if (finder == null){
            //return new Result(Result.DECISION_NOT_APPLICABLE, context.getResourceId().encode());
            return ResultFactory.getFactory().getResult(Result.DECISION_NOT_APPLICABLE, context);
        }

        PolicyFinderResult pfr = finder.findPolicy(reference, policyType, constraints,
                parentMetaData);

        // if we found nothing, then we return NotApplicable
        if (pfr.notApplicable()){
            //return new Result(Result.DECISION_NOT_APPLICABLE, context.getResourceId().encode());
            return ResultFactory.getFactory().getResult(Result.DECISION_NOT_APPLICABLE, context);
        }
        // if there was an error, we return that status data
        if (pfr.indeterminate()){
//            return new Result(Result.DECISION_INDETERMINATE, pfr.getStatus(), context
//                    .getResourceId().encode());
            return ResultFactory.getFactory().getResult(Result.DECISION_INDETERMINATE, pfr.getStatus(), context);
        }
        // we must have found a policy
        return pfr.getPolicy().evaluate(context);
    }
 
Example #9
Source File: PermitUnlessDenyRuleAlg.java    From balana with Apache License 2.0 6 votes vote down vote up
@Override
public AbstractResult combine(EvaluationCtx context, List parameters, List ruleElements) {

    List<ObligationResult> permitObligations = new ArrayList<ObligationResult>();
    List<Advice> permitAdvices= new ArrayList<Advice>();

    for (Object ruleElement : ruleElements) {
        Rule rule = ((RuleCombinerElement) (ruleElement)).getRule();
        AbstractResult result = rule.evaluate(context);
        int value = result.getDecision();

        // if there was a value of DENY, then regardless of what else
        // we've seen, we always return DENY
        if (value == AbstractResult.DECISION_DENY) {
            return result;
        } else if(value == AbstractResult.DECISION_PERMIT){
            permitObligations.addAll(result.getObligations());
            permitAdvices.addAll(result.getAdvices());
        }
    }

    // if there is not any value of DENY. The return PERMIT
    return ResultFactory.getFactory().getResult(AbstractResult.DECISION_PERMIT,
                                                permitObligations, permitAdvices, context);
}
 
Example #10
Source File: PermitUnlessDenyPolicyAlg.java    From balana with Apache License 2.0 5 votes vote down vote up
@Override
public AbstractResult combine(EvaluationCtx context, List parameters, List policyElements) {

    List<ObligationResult> permitObligations = new ArrayList<ObligationResult>();
    List<Advice> permitAdvices= new ArrayList<Advice>();

    for (Object policyElement : policyElements) {
        AbstractPolicy policy = ((PolicyCombinerElement) (policyElement)).getPolicy();
        MatchResult match = policy.match(context);
        if (match.getResult() == MatchResult.MATCH) {
            AbstractResult result = policy.evaluate(context);
            int value = result.getDecision();

            // if there was a value of DENY, then regardless of what else
            // we've seen, we always return DENY
            if (value == AbstractResult.DECISION_DENY) {
                return result;
            } else if (value == AbstractResult.DECISION_PERMIT) {
                permitObligations.addAll(result.getObligations());
                permitAdvices.addAll(result.getAdvices());
            }
        }
    }

    // if there is not any value of DENY. The return PERMIT
    return ResultFactory.getFactory().getResult(AbstractResult.DECISION_PERMIT,
                                                permitObligations, permitAdvices, context);
}
 
Example #11
Source File: FirstApplicablePolicyAlg.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Applies the combining rule to the set of policies based on the evaluation context.
 * 
 * @param context the context from the request
 * @param parameters a (possibly empty) non-null <code>List</code> of
 *            <code>CombinerParameter<code>s
 * @param policyElements the policies to combine
 * 
 * @return the result of running the combining algorithm
 */
public AbstractResult combine(EvaluationCtx context, List parameters, List policyElements) {
    Iterator it = policyElements.iterator();
    while (it.hasNext()) {
        AbstractPolicy policy = ((PolicyCombinerElement) (it.next())).getPolicy();

        // make sure that the policy matches the context
        MatchResult match = policy.match(context);

        if (match.getResult() == MatchResult.INDETERMINATE)
            return ResultFactory.getFactory().getResult(AbstractResult.DECISION_INDETERMINATE,
                    match.getStatus(), context);
        if (match.getResult() == MatchResult.MATCH) {
            // evaluate the policy
            AbstractResult result = policy.evaluate(context);
            int effect = result.getDecision();

            // in the case of PERMIT, DENY, or INDETERMINATE, we always
            // just return that result, so only on a rule that doesn't
            // apply do we keep going...
            if (effect != Result.DECISION_NOT_APPLICABLE && !context.isSearching()) {
                return result;
            }
        }
    }
    // if we got here, then none of the rules applied
    return ResultFactory.getFactory().getResult(AbstractResult.DECISION_NOT_APPLICABLE, context);
}
 
Example #12
Source File: JSONResponseWriter.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Returns <code>JsonObject</code> created by parsing the contents of a given
 * Balana <code>{@link ResponseCtx}</code>
 *
 * @param response <code>{@link ResponseCtx}</code>
 * @return <code>{@link JsonObject}</code> with parsed properties
 * @throws ResponseWriteException <code>{@link ResponseWriteException}</code>
 */
public static JsonObject write(ResponseCtx response) throws ResponseWriteException {

    JsonObject responseWrap = new JsonObject();

    //JsonObject jsonResponse = new JsonObject();
    JsonArray results = new JsonArray();

    Properties properties = EntitlementUtil.getPropertiesFromEntitlementConfig();
    if (properties != null) {
        if (Boolean.parseBoolean(properties.getProperty(PDPConstants.XACML_JSON_SHORT_FORM_ENABLED))) {
            xacmlJSONProfileShortFormEnable = true;
        }
    }
    //Loop all AbstractResult objects in ResponseCtx and add them as
    //Requests to JSON Response
    //There should be at least 1 request
    if (response.getResults().size() < 1) {
        throw new ResponseWriteException(40032, "XACML response should contain at least 1 Result");
    }

    for (AbstractResult result : response.getResults()) {
        /* AbstractResult type does not contain PolicyIdentifierList, as per XACML 3.0, the PolicyIdentifier is
        optional. Hence, Result type is not used. */
        results.add(abstractResultToJSONObject(result));
    }
    responseWrap.add(EntitlementEndpointConstants.RESPONSE, results);

    return responseWrap;
}
 
Example #13
Source File: DenyUnlessPermitPolicyAlg.java    From balana with Apache License 2.0 5 votes vote down vote up
@Override
public AbstractResult combine(EvaluationCtx context, List parameters, List policyElements) {

    List<ObligationResult> denyObligations = new ArrayList<ObligationResult>();
    List<Advice> denyAdvices = new ArrayList<Advice>();

    for (Object policyElement : policyElements) {
        AbstractPolicy policy = ((PolicyCombinerElement) (policyElement)).getPolicy();
        MatchResult match = policy.match(context);
        if (match.getResult() == MatchResult.MATCH) {
            AbstractResult result = policy.evaluate(context);
            int value = result.getDecision();
            // if there was a value of PERMIT, then regardless of what else
            // we've seen, we always return PERMIT
            if (value == AbstractResult.DECISION_PERMIT) {
                return result;
            } else if(value == AbstractResult.DECISION_DENY){
                denyObligations.addAll(result.getObligations());
                denyAdvices.addAll(result.getAdvices());
            }
        }
    }

    // if there is not any value of PERMIT. The return DENY
    return ResultFactory.getFactory().getResult(AbstractResult.DECISION_DENY, denyObligations,
                                                                        denyAdvices, context);
}
 
Example #14
Source File: TestJSONResponseWriter.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteWithObligations() throws URISyntaxException {

    List<AttributeAssignment> assignments = new ArrayList<>();
    String content = "Error: Channel request is not WEB.";
    URI type = new URI("http://www.w3.org/2001/XMLSchema#string");
    URI attributeId = new URI("urn:oasis:names:tc:xacml:3.0:example:attribute:text");
    AttributeAssignment attributeAssignment = new AttributeAssignment(attributeId, type, null, content, null);
    assignments.add(attributeAssignment);

    List<ObligationResult> obligationResults = new ArrayList<>();
    ObligationResult obligationResult = new Obligation(assignments, new URI("channel_ko"));
    obligationResults.add(obligationResult);

    List<String> codes = new ArrayList<>();
    codes.add("urn:oasis:names:tc:xacml:1.0:status:ok");
    AbstractResult abstractResult = new Result(1, new Status(codes), obligationResults, null, null);

    ResponseCtx responseCtx = new ResponseCtx(abstractResult);

    JSONResponseWriter jsonResponseWriter = new JSONResponseWriter();
    try {
        JsonObject jsonObject = jsonResponseWriter.write(responseCtx);
        assertNotNull("Failed to build the XACML json response", jsonObject.toString());
        assertFalse("Failed to build the XACML json response", jsonObject.entrySet().isEmpty());
        for(Map.Entry<String, JsonElement> jsonElementEntry: jsonObject.entrySet()) {
            if (jsonElementEntry.getKey().equals("Response")) {
                JsonArray jsonArray = (JsonArray) jsonElementEntry.getValue();
                assertEquals("Failed to build the XACML json response with correct evaluation",
                        jsonArray.get(0).getAsJsonObject().get("Decision").getAsString(), "Deny");
            }
        }
    } catch (ResponseWriteException e) {
        assertNull("Failed to build the XACML response", e);
    }

}
 
Example #15
Source File: ObligationExpression.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Encodes this <code>ObligationExpression</code> into its XML form and writes this out to the provided
 * <code>StringBuilder<code>
 *
 * @param builder string stream into which the XML-encoded data is written
 */
public void encode(StringBuilder builder) {

    builder.append("<ObligationExpression ObligationId=\"").append(obligationId.toString()).
            append("\" FulfillOn=\"").append(AbstractResult.DECISIONS[fulfillOn]).append("\">\n");
    for (AttributeAssignmentExpression assignment : expressions) {
        assignment.encode(builder);
    }
    builder.append("</ObligationExpression>");
}
 
Example #16
Source File: PDPController.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Evaluates the request which was created based on KMarket sample.
 *
 * @param request is going to be converted to XACML Request.
 * @return        result of the Policy Decision Point.
 * */
@PostMapping("/evaluate")
public ResponseObject evaluate(@RequestBody RequestObject request)
{
    int totalAmount = 0;
    Utilities.initData();
    Utilities.initBalana();

    totalAmount = Utilities.calculateTotal(request.getProductName(), request.getNumberOfProducts());
    String xacmlRequest = Utilities.createXACMLRequest(
            request.getUsername(), request.getProductName(), request.getNumberOfProducts(), totalAmount);

    PDP pdp = Utilities.getPDPNewInstance();
    String xacmlResponse = pdp.evaluate(xacmlRequest); //evaluates XACML request here.
    String responseMessage = "";

    try {
        ResponseCtx responseCtx = ResponseCtx.getInstance(Utilities.getXacmlResponse(xacmlResponse));
        AbstractResult result  = responseCtx.getResults().iterator().next();
        if(AbstractResult.DECISION_PERMIT == result.getDecision()){
            responseMessage = "\n" + request.getUsername() + " is authorized to perform this purchase\n\n";
        } else {
            //if it is not PERMIT, DENY is going to be returned to client user.
            responseMessage += "\n" + request.getUsername() + " is NOT authorized to perform this purchase\n";
            List<Advice> advices = result.getAdvices();
            for(Advice advice : advices){
                List<AttributeAssignment> assignments = advice.getAssignments();
                for(AttributeAssignment assignment : assignments){
                    responseMessage += "Advice :  " + assignment.getContent() +"\n\n";
                }
            }
        }
    } catch (ParsingException e) {
        e.printStackTrace();
    }
    return new ResponseObject(responseMessage);
}
 
Example #17
Source File: TestJSONResponseWriter.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteWithAdvices() throws URISyntaxException {

    List<AttributeAssignment> assignments = new ArrayList<>();
    String content = "Error: Channel request is not WEB.";
    URI type = new URI("http://www.w3.org/2001/XMLSchema#string");
    URI attributeId = new URI("urn:oasis:names:tc:xacml:3.0:example:attribute:text");
    AttributeAssignment attributeAssignment = new AttributeAssignment(attributeId, type, null, content, null);
    assignments.add(attributeAssignment);

    List<Advice> adviceResults = new ArrayList<>();
    Advice adviceResult = new Advice(new URI("channel_ko"), assignments);
    adviceResults.add(adviceResult);

    List<String> codes = new ArrayList<>();
    codes.add("urn:oasis:names:tc:xacml:1.0:status:ok");
    AbstractResult abstractResult = new Result(1, new Status(codes), null, adviceResults, null);

    ResponseCtx responseCtx = new ResponseCtx(abstractResult);

    JSONResponseWriter jsonResponseWriter = new JSONResponseWriter();
    try {
        JsonObject jsonObject = jsonResponseWriter.write(responseCtx);
        assertNotNull("Failed to build the XACML json response", jsonObject.toString());
        assertFalse("Failed to build the XACML json response", jsonObject.entrySet().isEmpty());
        for(Map.Entry<String, JsonElement> jsonElementEntry: jsonObject.entrySet()) {
            if (jsonElementEntry.getKey().equals("Response")) {
                JsonArray jsonArray = (JsonArray) jsonElementEntry.getValue();
                assertEquals("Failed to build the XACML json response with correct evaluation",
                        jsonArray.get(0).getAsJsonObject().get("Decision").getAsString(), "Deny");
            }
        }
    } catch (ResponseWriteException e) {
        assertNull("Failed to build the XACML json response", e);
    }

}
 
Example #18
Source File: AdviceExpression.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Encodes this <code>ObligationExpression</code> into its XML form and writes this out to the provided
 * <code>StringBuilder<code>
 *
 * @param builder string stream into which the XML-encoded data is written
 */
public void encode(StringBuilder builder) {

    builder.append("<AdviceExpression AdviceId=\"" + adviceId + "\" AppliesTo=\""
            + AbstractResult.DECISIONS[appliesTo] + "\">");
    for (AttributeAssignmentExpression assignment : attributeAssignmentExpressions) {
        assignment.encode(builder);
    }
    builder.append("</AdviceExpression>");
}
 
Example #19
Source File: DenyOverridesRuleAlg.java    From balana with Apache License 2.0 4 votes vote down vote up
/**
 * Applies the combining rule to the set of rules based on the evaluation context.
 *
 * @param context the context from the request
 * @param parameters a (possibly empty) non-null <code>List</code> of
 *            <code>CombinerParameter<code>s
 * @param ruleElements the rules to combine
 *
 * @return the result of running the combining algorithm
 */
public AbstractResult combine(EvaluationCtx context, List parameters, List ruleElements) {
    
    boolean atLeastOneError = false;
    boolean potentialDeny = false;
    boolean atLeastOnePermit = false;
    AbstractResult firstIndeterminateResult = null;
    List<ObligationResult> permitObligations = new ArrayList<ObligationResult>();
    List<Advice> permitAdvices = new ArrayList<Advice>();
    Iterator it = ruleElements.iterator();

    while (it.hasNext()) {
        Rule rule = ((RuleCombinerElement) (it.next())).getRule();
        AbstractResult result = rule.evaluate(context);
        int value = result.getDecision();

        // if there was a value of DENY, then regardless of what else
        // we've seen, we always return DENY
        if (value == AbstractResult.DECISION_DENY){     // TODO  -- i changed
            return result;
        }
        // if it was INDETERMINATE, then we couldn't figure something
        // out, so we keep track of these cases...
        if (value == AbstractResult.DECISION_INDETERMINATE ||
                value == AbstractResult.DECISION_INDETERMINATE_DENY ||
                value == AbstractResult.DECISION_INDETERMINATE_PERMIT ||
                value == AbstractResult.DECISION_INDETERMINATE_DENY_OR_PERMIT) {
            
            atLeastOneError = true;

            // there are no rules about what to do if multiple cases
            // cause errors, so we'll just return the first one
            if (firstIndeterminateResult == null){
                firstIndeterminateResult = result;
            }
            // if the Rule's effect is DENY, then we can't let this
            // alg return PERMIT, since this Rule might have denied
            // if it could do its stuff
            if (rule.getEffect() == AbstractResult.DECISION_DENY){
                potentialDeny = true;
            }
        } else {
            // keep track of whether we had at least one rule that
            // actually pertained to the request
            if (value == AbstractResult.DECISION_PERMIT){
                atLeastOnePermit = true;
                permitAdvices.addAll(result.getAdvices());
                permitObligations.addAll(result.getObligations());
            }

        }
    }

    // we didn't explicitly DENY, but we might have had some Rule
    // been evaluated, so we have to return INDETERMINATE
    if (potentialDeny){
        return firstIndeterminateResult;
    }
    // some Rule said PERMIT, so since nothing could have denied,
    // we return PERMIT
    if (atLeastOnePermit) {
        return ResultFactory.getFactory().getResult(AbstractResult.DECISION_PERMIT,
                                                    permitObligations, permitAdvices, context);            
    }


    // we didn't find anything that said PERMIT, but if we had a
    // problem with one of the Rules, then we're INDETERMINATE
    if (atLeastOneError){
        return firstIndeterminateResult;
    }
    // if we hit this point, then none of the rules actually applied
    // to us, so we return NOT_APPLICABLE
    //return new Result(Result.DECISION_NOT_APPLICABLE, context.getResourceId().encode());
    return ResultFactory.getFactory().getResult(AbstractResult.DECISION_NOT_APPLICABLE, context);
}
 
Example #20
Source File: JSONResponseWriter.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
/**
 * Private method to convert a given Balana <code>{@link AbstractResult}</code> to a <code>{@link JsonObject}</code>
 *
 * @param result <code>{@link AbstractResult}</code>
 * @return <code>{@link JsonObject}</code>
 * @throws ResponseWriteException <code>{@link ResponseWriteException}</code>
 */
private static JsonObject abstractResultToJSONObject(AbstractResult result) throws ResponseWriteException {

    JsonObject jsonResult = new JsonObject();

    //Decision property is mandatory, if not set throw error
    if (result.getDecision() == -1) {
        throw new ResponseWriteException(40031, "XACML Result should contain the Decision");
    }
    jsonResult.addProperty(EntitlementEndpointConstants.DECISION,
            AbstractResult.DECISIONS[result.getDecision()]);

    //If Status object is present, convert it
    if (result.getStatus() != null) {
        jsonResult.add(EntitlementEndpointConstants.STATUS, statusToJSONObject(result.getStatus()));
    }

    //If Obligations are present
    if (result.getObligations() != null && !result.getObligations().isEmpty()) {
        //can only get ObligationResult objects from balana
        JsonArray obligations = new JsonArray();
        for (ObligationResult obligation : result.getObligations()) {
            if (obligation instanceof Obligation) {
                obligations.add(obligationToJsonObject((Obligation) obligation));
            } else {
                obligations.add(new JsonPrimitive(obligation.encode()));
            }
        }

        jsonResult.add(EntitlementEndpointConstants.OBLIGATIONS, obligations);
    }

    // Do the same with attributes
    if (result.getAdvices() != null && !result.getAdvices().isEmpty()) {
        //can only get ObligationResult objects from balana
        JsonArray advices = new JsonArray();
        for (Advice advice : result.getAdvices()) {
            advices.add(adviceToJsonObject(advice));
        }

        jsonResult.add(EntitlementEndpointConstants.ASSOCIATED_ADVICE, advices);
    }

    // If includeInResponse=true, other attributes will be populated from here with the decision.
    if (((Result) result).getAttributes() != null && !((Result) result).getAttributes().isEmpty()) {
        Set<Attributes> attributes = ((Result) result).getAttributes();

        for (Attributes attribute : attributes) {

            switch (attribute.getCategory().toString()) {
                case EntitlementEndpointConstants.CATEGORY_ACTION_URI:
                    jsonResult.add(EntitlementEndpointConstants.CATEGORY_ACTION, getJsonObject(attribute));
                    break;

                case EntitlementEndpointConstants.CATEGORY_RESOURCE_URI:
                    jsonResult.add(EntitlementEndpointConstants.CATEGORY_RESOURCE, getJsonObject(attribute));
                    break;

                case EntitlementEndpointConstants.CATEGORY_ACCESS_SUBJECT_URI:
                    jsonResult.add(EntitlementEndpointConstants.CATEGORY_ACCESS_SUBJECT, getJsonObject(attribute));
                    break;

                case EntitlementEndpointConstants.CATEGORY_ENVIRONMENT_URI:
                    jsonResult.add(EntitlementEndpointConstants.CATEGORY_ENVIRONMENT, getJsonObject(attribute));
                    break;

                case EntitlementEndpointConstants.CATEGORY_RECIPIENT_SUBJECT_URI:
                    jsonResult.add(EntitlementEndpointConstants.CATEGORY_RECIPIENT_SUBJECT,
                            getJsonObject(attribute));
                    break;

                case EntitlementEndpointConstants.CATEGORY_INTERMEDIARY_SUBJECT_URI:
                    jsonResult.add(EntitlementEndpointConstants.CATEGORY_INTERMEDIARY_SUBJECT,
                            getJsonObject(attribute));
                    break;

                case EntitlementEndpointConstants.CATEGORY_CODEBASE_URI:
                    jsonResult.add(EntitlementEndpointConstants.CATEGORY_CODEBASE, getJsonObject(attribute));
                    break;

                case EntitlementEndpointConstants.CATEGORY_REQUESTING_MACHINE_URI:
                    jsonResult.add(EntitlementEndpointConstants.CATEGORY_REQUESTING_MACHINE,
                            getJsonObject(attribute));
                    break;

                default:
                    jsonResult.add(attribute.getCategory().toString(), getJsonObject(attribute));
                    break;
            }
        }
    }

    return jsonResult;
}
 
Example #21
Source File: Result.java    From balana with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new instance of a <code>Result</code> based on the given
 * DOM root node. A <code>ParsingException</code> is thrown if the DOM
 * root doesn't represent a valid ResultType.
 *
 * @param root the DOM root of a ResultType
 *
 * @return a new <code>Result</code>
 *
 * @throws ParsingException if the node is invalid
 */
public static AbstractResult getInstance(Node root) throws ParsingException {
    
    int decision = -1;
    Status status = null;
    String resource = null;
    List<ObligationResult> obligations = null;

    NamedNodeMap attrs = root.getAttributes();
    Node resourceAttr = attrs.getNamedItem("ResourceId");
    if (resourceAttr != null){
        resource = resourceAttr.getNodeValue();
    }
    NodeList nodes = root.getChildNodes();
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        String name = DOMHelper.getLocalName(node);

        if (name.equals("Decision")) {
            String type = node.getFirstChild().getNodeValue();
            for (int j = 0; j < DECISIONS.length; j++) {
                if (DECISIONS[j].equals(type)) {
                    decision = j;
                    break;
                }
            }

            if (decision == -1)
                throw new ParsingException("Unknown Decision: " + type);
        } else if (name.equals("Status")) {
            if(status == null){
                status = Status.getInstance(node);
            } else {
                throw new ParsingException("More than one StatusType defined");      
            }
        } else if (name.equals("Obligations")) {
            if(obligations == null){
                obligations = parseObligations(node);
            } else {
                throw new ParsingException("More than one ObligationsType defined");    
            }
        }
    }

    return new Result(decision, status, obligations, resource);
}
 
Example #22
Source File: Result.java    From balana with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new instance of a <code>Result</code> based on the given
 * DOM root node. A <code>ParsingException</code> is thrown if the DOM
 * root doesn't represent a valid ResultType.
 *
 * @param root the DOM root of a ResultType
 *
 * @return a new <code>Result</code>
 *
 * @throws ParsingException if the node is invalid
 */
public static AbstractResult getInstance(Node root) throws ParsingException {

    int decision = -1;
    Status status = null;
    List<ObligationResult> obligations = null;
    List<Advice> advices = null;
    Set<PolicyReference> policyReferences = null;
    Set<Attributes>  attributes = null;

    NodeList nodes = root.getChildNodes();
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        String name = DOMHelper.getLocalName(node);

        if (name.equals("Decision")) {
            String type = node.getFirstChild().getNodeValue();
            for (int j = 0; j < DECISIONS.length; j++) {
                if (DECISIONS[j].equals(type)) {
                    decision = j;
                    break;
                }
            }

            if (decision == -1){
                throw new ParsingException("Unknown Decision: " + type);
            }
        } else if (name.equals("Status")) {
            if(status == null){
                status = Status.getInstance(node);
            } else {
                throw new ParsingException("More than one StatusType defined");
            }
        } else if (name.equals("Obligations")) {
            if(obligations == null){
                obligations = parseObligations(node);
            } else {
                throw new ParsingException("More than one ObligationsType defined");
            }
        } else if (name.equals("AssociatedAdvice")) {
            if(advices == null){
                advices = parseAdvices(node);
            } else {
                throw new ParsingException("More than one AssociatedAdviceType defined"); 
            }
        } else if (name.equals("PolicyIdentifierList")){
            if(policyReferences == null){
                policyReferences = parsePolicyReferences(node);
            } else {
                throw new ParsingException("More than one PolicyIdentifierListType defined"); 
            }
        } else if(name.equals("Attributes")){
            if(attributes == null){
                attributes = new HashSet<Attributes>();
            }
            attributes.add(Attributes.getInstance(node));    
        }
    }

    return new Result(decision, status, obligations, advices, policyReferences, attributes);
}
 
Example #23
Source File: DenyOverridesPolicyAlg.java    From balana with Apache License 2.0 4 votes vote down vote up
/**
 * Applies the combining rule to the set of policies based on the evaluation context.
 * 
 * @param context the context from the request
 * @param parameters a (possibly empty) non-null <code>List</code> of
 *            <code>CombinerParameter<code>s
 * @param policyElements the policies to combine
 * 
 * @return the result of running the combining algorithm
 */
public AbstractResult combine(EvaluationCtx context, List parameters, List policyElements) {
    boolean atLeastOnePermit = false;
    List<ObligationResult> permitObligations = new ArrayList<ObligationResult>();
    List<Advice> permitAdvices= new ArrayList<Advice>();
    Iterator it = policyElements.iterator();

    while (it.hasNext()) {
        AbstractPolicy policy = ((PolicyCombinerElement) (it.next())).getPolicy();
        // make sure that the policy matches the context
        MatchResult match = policy.match(context);

        if (match.getResult() == MatchResult.INDETERMINATE){ //TODO  do we really want this?
            return ResultFactory.getFactory().getResult(AbstractResult.DECISION_DENY, context);
        }

        if (match.getResult() == MatchResult.MATCH) {
            // evaluate the policy
            AbstractResult result = policy.evaluate(context);
            int effect = result.getDecision();

            // unlike in the RuleCombining version of this alg, we always
            // return DENY if any Policy returns DENY or INDETERMINATE
            if (effect == AbstractResult.DECISION_DENY){
                return result;
            }
            
            if (effect == AbstractResult.DECISION_INDETERMINATE ||
                effect == AbstractResult.DECISION_INDETERMINATE_DENY ||
                effect == AbstractResult.DECISION_INDETERMINATE_PERMIT ||
                effect == AbstractResult.DECISION_INDETERMINATE_DENY_OR_PERMIT) {
                
                return ResultFactory.getFactory().getResult(Result.DECISION_DENY, context);
            }
            // remember if at least one Policy said PERMIT
            if (effect == Result.DECISION_PERMIT) {
                atLeastOnePermit = true;
                permitAdvices.addAll(result.getAdvices());
                permitObligations.addAll(result.getObligations());
            }
        }
    }

    // if we got a PERMIT, return it, otherwise it's NOT_APPLICABLE
    if (atLeastOnePermit) {
        return ResultFactory.getFactory().getResult(AbstractResult.DECISION_PERMIT,
                                                    permitObligations, permitAdvices, context);
    } else {
        return ResultFactory.getFactory().getResult(AbstractResult.DECISION_NOT_APPLICABLE, context); 
    }
}
 
Example #24
Source File: PermitOverridesRuleAlg.java    From balana with Apache License 2.0 4 votes vote down vote up
/**
 * Applies the combining rule to the set of rules based on the evaluation context.
 *
 * @param context the context from the request
 * @param parameters a (possibly empty) non-null <code>List</code> of
 *            <code>CombinerParameter<code>s
 * @param ruleElements the rules to combine
 *
 * @return the result of running the combining algorithm
 */
public AbstractResult combine(EvaluationCtx context, List parameters, List ruleElements) {
    boolean atLeastOneError = false;
    boolean potentialPermit = false;
    boolean atLeastOneDeny = false;
    AbstractResult firstIndeterminateResult = null;
    List<ObligationResult> denyObligations = new ArrayList<ObligationResult>();
    List<Advice> denyAdvices = new ArrayList<Advice>();
    Iterator it = ruleElements.iterator();

    while (it.hasNext()) {
        Rule rule = ((RuleCombinerElement) (it.next())).getRule();
        AbstractResult result = rule.evaluate(context);
        int value = result.getDecision();

        // if there was a value of PERMIT, then regardless of what
        // else we've seen, we always return PERMIT
        if (value == AbstractResult.DECISION_PERMIT){
            return result;
        }
        // if it was INDETERMINATE, then we couldn't figure something
        // out, so we keep track of these cases...
        if (value == AbstractResult.DECISION_INDETERMINATE ||
                value == AbstractResult.DECISION_INDETERMINATE_DENY ||
                value == AbstractResult.DECISION_INDETERMINATE_PERMIT ||
                value == AbstractResult.DECISION_INDETERMINATE_DENY_OR_PERMIT) {
            
            atLeastOneError = true;

            // there are no rules about what to do if multiple cases
            // cause errors, so we'll just return the first one
            if (firstIndeterminateResult == null){
                firstIndeterminateResult = result;
            }
            // if the Rule's effect is PERMIT, then we can't let this
            // alg return DENY, since this Rule might have permitted
            // if it could do its stuff
            if (rule.getEffect() == AbstractResult.DECISION_PERMIT){
                potentialPermit = true;
            }
        } else {
            // keep track of whether we had at least one rule that
            // actually pertained to the request
            if (value == AbstractResult.DECISION_DENY)
                atLeastOneDeny = true;
                denyAdvices.addAll(result.getAdvices());
                denyObligations.addAll(result.getObligations());
        }
    }

    // we didn't explicitly PERMIT, but we might have had some Rule
    // been evaluated, so we have to return INDETERMINATE
    if (potentialPermit){
        return firstIndeterminateResult;
    }
    // some Rule said DENY, so since nothing could have permitted,
    // we return DENY
    if (atLeastOneDeny){
        return ResultFactory.getFactory().getResult(AbstractResult.DECISION_DENY, denyObligations,
                                                                        denyAdvices, context);
    }
    // we didn't find anything that said DENY, but if we had a
    // problem with one of the Rules, then we're INDETERMINATE
    if (atLeastOneError){
        return firstIndeterminateResult;
    }
    // if we hit this point, then none of the rules actually applied
    // to us, so we return NOT_APPLICABLE
    return ResultFactory.getFactory().getResult(AbstractResult.DECISION_NOT_APPLICABLE, context);
}
 
Example #25
Source File: Main.java    From balana with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args){

        Console console;
        String userName = "none";
        String content = "foo";

        initBalana();
        
        if ((console = System.console()) != null){
            userName = console.readLine("Enter User name  [bob,  peter, alice] : ");
            if(userName == null || userName.trim().length() < 1 ){
                System.err.println("\nUser name can not be empty\n");
                return;
            }
        }

        String request = createXACMLRequest(userName, content);

        PDP pdp = getPDPNewInstance();

        System.out.println("\n======================== XACML Request ====================");
        System.out.println(request);
        System.out.println("===========================================================");

        String response = pdp.evaluate(request);

        System.out.println("\n======================== XACML Response ===================");
        System.out.println(response);
        System.out.println("===========================================================");

        try {
            ResponseCtx responseCtx = ResponseCtx.getInstance(getXacmlResponse(response));
            AbstractResult result  = responseCtx.getResults().iterator().next();
            if(AbstractResult.DECISION_PERMIT == result.getDecision()){
                System.out.println("\n" + userName + " is authorized to perform this access\n\n");
            } else {
                System.out.println("\n" + userName + " is NOT authorized to perform this access\n");
            }
        } catch (ParsingException e) {
            e.printStackTrace();
        }

    }
 
Example #26
Source File: PermitOverridesPolicyAlg.java    From balana with Apache License 2.0 4 votes vote down vote up
/**
 * Applies the combining rule to the set of policies based on the evaluation context.
 * 
 * @param context the context from the request
 * @param parameters a (possibly empty) non-null <code>List</code> of
 *            <code>CombinerParameter<code>s
 * @param policyElements the policies to combine
 *
 * @return the result of running the combining algorithm
 */
public AbstractResult combine(EvaluationCtx context, List parameters, List policyElements) {
    boolean atLeastOneError = false;
    boolean atLeastOneDeny = false;
    List<ObligationResult> denyObligations = new ArrayList<ObligationResult>();
    List<Advice> denyAdvices = new ArrayList<Advice>();
    Status firstIndeterminateStatus = null;
    Iterator it = policyElements.iterator();

    while (it.hasNext()) {
        AbstractPolicy policy = ((PolicyCombinerElement) (it.next())).getPolicy();

        // make sure that the policy matches the context
        MatchResult match = policy.match(context);

        if (match.getResult() == MatchResult.INDETERMINATE) {
            atLeastOneError = true;

            // keep track of the first error, regardless of cause
            if (firstIndeterminateStatus == null){
                firstIndeterminateStatus = match.getStatus();
            }
        } else if (match.getResult() == MatchResult.MATCH) {
            // now we evaluate the policy
            AbstractResult result = policy.evaluate(context);
            int effect = result.getDecision();

            // this is a little different from DenyOverrides...

            if (effect == Result.DECISION_PERMIT)
                return result;

            if (effect == Result.DECISION_DENY) {
                atLeastOneDeny = true;
                denyAdvices.addAll(result.getAdvices());
                denyObligations.addAll(result.getObligations());
            } else if (effect == AbstractResult.DECISION_INDETERMINATE ||
                effect == AbstractResult.DECISION_INDETERMINATE_DENY ||
                effect == AbstractResult.DECISION_INDETERMINATE_PERMIT ||
                effect == AbstractResult.DECISION_INDETERMINATE_DENY_OR_PERMIT) {
                
                atLeastOneError = true;
                // keep track of the first error, regardless of cause
                if (firstIndeterminateStatus == null)
                    firstIndeterminateStatus = result.getStatus();
            }
        }
    }

    // if we got a DENY, return it
    if (atLeastOneDeny){
        return ResultFactory.getFactory().getResult(Result.DECISION_DENY, denyObligations,
                                                                        denyAdvices, context);
    }
    // if we got an INDETERMINATE, return it
    if (atLeastOneError){
        return ResultFactory.getFactory().getResult(Result.DECISION_INDETERMINATE,
                firstIndeterminateStatus, context);
    }

    // if we got here, then nothing applied to us
    //return new Result(Result.DECISION_NOT_APPLICABLE, context.getResourceId().encode());
    return ResultFactory.getFactory().getResult(Result.DECISION_NOT_APPLICABLE, context);
}
 
Example #27
Source File: OnlyOneApplicablePolicyAlg.java    From balana with Apache License 2.0 4 votes vote down vote up
/**
 * Applies the combining rule to the set of policies based on the evaluation context.
 * 
 * @param context the context from the request
 * @param parameters a (possibly empty) non-null <code>List</code> of
 *            <code>CombinerParameter<code>s
 * @param policyElements the policies to combine
 * 
 * @return the result of running the combining algorithm
 */
public AbstractResult combine(EvaluationCtx context, List parameters, List policyElements) {
    boolean atLeastOne = false;
    AbstractPolicy selectedPolicy = null;
    Iterator it = policyElements.iterator();

    while (it.hasNext()) {
        AbstractPolicy policy = ((PolicyCombinerElement) (it.next())).getPolicy();

        // see if the policy matches the context
        MatchResult match = policy.match(context);
        int result = match.getResult();

        // if there is an error in trying to match any of the targets,
        // we always return INDETERMINATE immediately
        if (result == MatchResult.INDETERMINATE){
            return ResultFactory.getFactory().getResult(AbstractResult.DECISION_INDETERMINATE,
                    match.getStatus(),context);
        }
        if (result == MatchResult.MATCH) {
            // if this isn't the first match, then this is an error
            if (atLeastOne) {
                List code = new ArrayList();
                code.add(Status.STATUS_PROCESSING_ERROR);
                String message = "Too many applicable policies";
                    return ResultFactory.getFactory().
                            getResult(AbstractResult.DECISION_INDETERMINATE,
                                    new Status(code, message), context);                     
            }

            // if this was the first applicable policy in the set, then
            // remember it for later
            atLeastOne = true;
            selectedPolicy = policy;
        }
    }

    // if we got through the loop and found exactly one match, then
    // we return the evaluation result of that policy
    if (atLeastOne){
        return selectedPolicy.evaluate(context);
    }
    // if we didn't find a matching policy, then we don't apply
    return ResultFactory.getFactory().getResult(AbstractResult.DECISION_NOT_APPLICABLE, context);
}
 
Example #28
Source File: KMarketAccessControl.java    From balana with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args){

        Console console;
        String userName = null;
        String productName = null;
        int numberOfProducts = 1;
        int totalAmount = 0;


        printDescription();

        initData();

        initBalana();

        System.out.println("\nYou can select one of following item for your shopping chart : \n");

        System.out.println(products);    

        if ((console = System.console()) != null){
            userName = console.readLine("Enter User name : ");
            if(userName == null || userName.trim().length() < 1 ){
                System.err.println("\nUser name can not be empty\n");
                return;
            }

            String productId = console.readLine("Enter Product Id : ");
            if(productId == null || productId.trim().length() < 1 ){
                System.err.println("\nProduct Id can not be empty\n");
                return;
            } else {
                productName = idMap.get(productId);
                if(productName == null){
                    System.err.println("\nEnter valid product Id\n");
                    return;
                }
            }

            String productAmount = console.readLine("Enter No of Products : ");
            if(productAmount == null || productAmount.trim().length() < 1 ){
                numberOfProducts = 1;
            } else {
                numberOfProducts = Integer.parseInt(productAmount);
            }
        }

        totalAmount = calculateTotal(productName, numberOfProducts);
        System.err.println("\nTotal Amount is  : " + totalAmount + "\n");


        String request = createXACMLRequest(userName, productName, numberOfProducts, totalAmount);
        //String request = createXACMLRequest("bob", "Food", 2, 40);
        PDP pdp = getPDPNewInstance();

        System.out.println("\n======================== XACML Request ====================");
        System.out.println(request);
        System.out.println("===========================================================");

        String response = pdp.evaluate(request);

        System.out.println("\n======================== XACML Response ===================");
        System.out.println(response);
        System.out.println("===========================================================");

        try {
            ResponseCtx responseCtx = ResponseCtx.getInstance(getXacmlResponse(response));
            AbstractResult result  = responseCtx.getResults().iterator().next();
            if(AbstractResult.DECISION_PERMIT == result.getDecision()){
                System.out.println("\n" + userName + " is authorized to perform this purchase\n\n");
            } else {
                System.out.println("\n" + userName + " is NOT authorized to perform this purchase\n");
                List<Advice> advices = result.getAdvices();
                for(Advice advice : advices){
                    List<AttributeAssignment> assignments = advice.getAssignments();
                    for(AttributeAssignment assignment : assignments){
                        System.out.println("Advice :  " + assignment.getContent() +"\n\n");
                    }
                }
            }
        } catch (ParsingException e) {
            e.printStackTrace();
        }

    }
 
Example #29
Source File: DenyOverridesRuleAlg.java    From balana with Apache License 2.0 4 votes vote down vote up
/**
 * Applies the combining rule to the set of rules based on the evaluation context.
 *
 * @param context the context from the request
 * @param parameters a (possibly empty) non-null <code>List</code> of
 *            <code>CombinerParameter<code>s
 * @param ruleElements the rules to combine
 *
 * @return the result of running the combining algorithm
 */
public AbstractResult combine(EvaluationCtx context, List parameters, List ruleElements) {

    boolean atLeastOneErrorD = false;
    boolean atLeastOneErrorP = false;
    boolean atLeastOnePermit = false;
    AbstractResult firstIndeterminateResultD = null;
    AbstractResult firstIndeterminateResultP = null;
    List<ObligationResult> permitObligations = new ArrayList<ObligationResult>();
    List<Advice> permitAdvices = new ArrayList<Advice>();
    Iterator it = ruleElements.iterator();

    while (it.hasNext()) {
        Rule rule = ((RuleCombinerElement) (it.next())).getRule();
        AbstractResult result = rule.evaluate(context);
        int value = result.getDecision();

        // if there was a value of DENY, then regardless of what else
        // we've seen, we always return DENY
        if (value == AbstractResult.DECISION_DENY){  
            return result;
        }

        if(value == AbstractResult.DECISION_NOT_APPLICABLE){
            continue;
        }

        // keep track of whether we had at least one rule that
        // actually pertained to the request
        if (value == AbstractResult.DECISION_PERMIT){

            atLeastOnePermit = true;
            permitAdvices.addAll(result.getAdvices());
            permitObligations.addAll(result.getObligations());
            
        } else {

            // if it was INDETERMINATE, check extended results
            if (value == AbstractResult.DECISION_INDETERMINATE_DENY){
                atLeastOneErrorD = true;
                // there are no rules about what to do if multiple cases
                // cause errors, so we'll just return the first one
                if(firstIndeterminateResultD == null){
                    firstIndeterminateResultD = result;
                }
            } else if (value== AbstractResult.DECISION_INDETERMINATE_PERMIT){
                atLeastOneErrorP = true;
                // there are no rules about what to do if multiple cases
                // cause errors, so we'll just return the first one
                if(firstIndeterminateResultP == null){
                    firstIndeterminateResultP = result;
                }
            }
        }
    }

    if (atLeastOneErrorD && (atLeastOneErrorP || atLeastOnePermit)){

        return ResultFactory.getFactory().getResult(AbstractResult.DECISION_INDETERMINATE_DENY_OR_PERMIT,
                                               firstIndeterminateResultD.getStatus(), context);
    }

    if(atLeastOneErrorD){
        return ResultFactory.getFactory().getResult(AbstractResult.DECISION_INDETERMINATE_DENY,
                                               firstIndeterminateResultD.getStatus(), context);
    }

    if (atLeastOnePermit) {
        return ResultFactory.getFactory().getResult(AbstractResult.DECISION_PERMIT,
                                                    permitObligations, permitAdvices, context);
    }

    if (atLeastOneErrorP){
        return ResultFactory.getFactory().getResult(AbstractResult.DECISION_INDETERMINATE_PERMIT,
                                               firstIndeterminateResultP.getStatus(), context);
    }

    // if we hit this point, then none of the rules actually applied
    // to us, so we return NOT_APPLICABLE
    return ResultFactory.getFactory().getResult(AbstractResult.DECISION_NOT_APPLICABLE, context);
}
 
Example #30
Source File: PermitOverridesRuleAlg.java    From balana with Apache License 2.0 4 votes vote down vote up
/**
 * Applies the combining rule to the set of rules based on the evaluation context.
 *
 * @param context the context from the request
 * @param parameters a (possibly empty) non-null <code>List</code> of
 *            <code>CombinerParameter<code>s
 * @param ruleElements the rules to combine
 *
 * @return the result of running the combining algorithm
 */
public AbstractResult combine(EvaluationCtx context, List parameters, List ruleElements) {

    boolean atLeastOneErrorD = false;
    boolean atLeastOneErrorP = false;
    boolean atLeastOneDeny = false;
    AbstractResult firstIndeterminateResultD = null;
    AbstractResult firstIndeterminateResultP = null;
    List<ObligationResult> denyObligations = new ArrayList<ObligationResult>();
    List<Advice> denyAdvices = new ArrayList<Advice>();

    Iterator it = ruleElements.iterator();

    while (it.hasNext()) {
        Rule rule = ((RuleCombinerElement) (it.next())).getRule();
        AbstractResult result = rule.evaluate(context);
        int value = result.getDecision();

        // if there was a value of PERMIT, then regardless of what
        // else we've seen, we always return PERMIT
        if (value == AbstractResult.DECISION_PERMIT){
            return result;
        }

        if(value == AbstractResult.DECISION_NOT_APPLICABLE){
            continue;
        }

        // keep track of whether we had at least one rule that
        // actually pertained to the request
        if (value == AbstractResult.DECISION_DENY){

            atLeastOneDeny = true;
            denyAdvices.addAll(result.getAdvices());
            denyObligations.addAll(result.getObligations());

        } else {

            // if it was INDETERMINATE, check extended results
            if (value == AbstractResult.DECISION_INDETERMINATE_DENY){
                atLeastOneErrorD = true;
                // there are no rules about what to do if multiple cases
                // cause errors, so we'll just return the first one
                if(firstIndeterminateResultD == null){
                    firstIndeterminateResultD = result;
                }
            } else if (value== AbstractResult.DECISION_INDETERMINATE_PERMIT){
                atLeastOneErrorP = true;
                // there are no rules about what to do if multiple cases
                // cause errors, so we'll just return the first one
                if(firstIndeterminateResultP == null){
                    firstIndeterminateResultP = result;
                }
            }
        }
    }

    if (atLeastOneErrorP && (atLeastOneErrorD || atLeastOneDeny)){

        return ResultFactory.getFactory().getResult(AbstractResult.DECISION_INDETERMINATE_DENY_OR_PERMIT,
                                               firstIndeterminateResultP.getStatus(), context);
    }

    if(atLeastOneErrorP){
        return ResultFactory.getFactory().getResult(AbstractResult.DECISION_INDETERMINATE_PERMIT,
                                               firstIndeterminateResultP.getStatus(), context);
    }

    if (atLeastOneDeny) {
        return ResultFactory.getFactory().getResult(AbstractResult.DECISION_DENY,
                                                    denyObligations, denyAdvices, context);
    }
    // if we hit this point, then none of the rules actually applied
    // to us, so we return NOT_APPLICABLE
    return ResultFactory.getFactory().getResult(AbstractResult.DECISION_NOT_APPLICABLE, context);
}