org.wso2.balana.ctx.Status Java Examples

The following examples show how to use org.wso2.balana.ctx.Status. 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: JSONResponseWriter.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Private method to convert Balana <code>{@link Status}</code> to <code>{@link JsonObject}</code>
 *
 * @param status <code>{@link Status}</code>
 * @return <code>{@link JsonObject}</code>
 */
private static JsonObject statusToJSONObject(Status status) {
    JsonObject jsonStatus = new JsonObject();

    jsonStatus.addProperty(EntitlementEndpointConstants.STATUS_MESSAGE, status.getMessage());

    if (status.getCode().size() > 0) {
        JsonObject statusCode = new JsonObject();
        statusCode.addProperty(EntitlementEndpointConstants.STATUS_CODE_VALUE, status.getCode().get(0));

        jsonStatus.add(EntitlementEndpointConstants.STATUS_CODE, statusCode);
    }
    if (status.getDetail() != null) {
        jsonStatus.addProperty(EntitlementEndpointConstants.STATUS_DETAIL, status.getDetail().getEncoded());
    }
    return jsonStatus;
}
 
Example #2
Source File: FileBasedPolicyFinderModule.java    From balana with Apache License 2.0 6 votes vote down vote up
@Override
public PolicyFinderResult findPolicy(URI idReference, int type, VersionConstraints constraints,
                                     PolicyMetaData parentMetaData) {

    AbstractPolicy policy = policies.get(idReference);
    if (policy != null) {
        if (type == PolicyReference.POLICY_REFERENCE) {
            if (policy instanceof Policy) {
                return new PolicyFinderResult(policy);
            }
        } else {
            if (policy instanceof PolicySet) {
                return new PolicyFinderResult(policy);
            }
        }
    }

    // if there was an error loading the policy, return the error
    ArrayList<String> code = new ArrayList<String>();
    code.add(Status.STATUS_PROCESSING_ERROR);
    Status status = new Status(code,
            "couldn't load referenced policy");
    return new PolicyFinderResult(status);
}
 
Example #3
Source File: MobiAttributeFinder.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public EvaluationResult findAttribute(URI attributeType, URI attributeId, String issuer, URI category,
                                      EvaluationCtx context) {
    if (!categoryIds.contains(category.toString())) {
        return new EvaluationResult(new Status(Collections.singletonList(Status.STATUS_PROCESSING_ERROR),
                "Unsupported category"));
    }

    BasicAttributeDesignator designator = new BasicAttributeDesignator(vf.createIRI(attributeId.toString()),
            vf.createIRI(category.toString()), vf.createIRI(attributeType.toString()));
    List<Literal> values = pip.findAttribute(designator, new BalanaRequest(context.getRequestCtx(), vf, jaxbContext));
    List<AttributeValue> attributeValues = new ArrayList<>();
    values.stream()
            .map(this::getAttributeValue)
            .forEach(attributeValues::add);

    return new EvaluationResult(new BagAttribute(attributeType, attributeValues));
}
 
Example #4
Source File: Target.java    From balana with Apache License 2.0 6 votes vote down vote up
/**
 * Determines whether this <code>Target</code> matches the input request (whether it is
 * applicable).
 *
 * @param context the representation of the request
 *
 * @return the result of trying to match the target and the request
 */
public MatchResult match(EvaluationCtx context) {

    Status firstIndeterminateStatus = null;

    for (AnyOfSelection anyOfSelection : anyOfSelections) {
        MatchResult result = anyOfSelection.match(context);
        if (result.getResult() == MatchResult.NO_MATCH){
            return result;
        } else if(result.getResult() == MatchResult.INDETERMINATE){
            if(firstIndeterminateStatus == null){
                firstIndeterminateStatus = result.getStatus();    
            }
        }
    }

    if(firstIndeterminateStatus == null){
        return new MatchResult(MatchResult.MATCH);
    } else {
        return new MatchResult(MatchResult.INDETERMINATE,
                               firstIndeterminateStatus);
    }
}
 
Example #5
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 #6
Source File: Result.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param decision
 * @param status
 * @param obligationResults
 * @param advices
 * @param evaluationCtx
 * @throws IllegalArgumentException
 */
public Result(int decision, Status status, List<ObligationResult> obligationResults,
              List<Advice> advices, EvaluationCtx evaluationCtx) throws IllegalArgumentException {
    super(decision, status, obligationResults, advices, XACMLConstants.XACML_VERSION_3_0);
    if(evaluationCtx != null){
        XACML3EvaluationCtx ctx = (XACML3EvaluationCtx) evaluationCtx;
        this.policyReferences = ctx.getPolicyReferences();
        processAttributes(ctx.getAttributesSet());
    }
}
 
Example #7
Source File: Rule.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Given the input context sees whether or not the request matches this <code>Rule</code>'s
 * <code>Target</code>. Note that unlike the matching done by the <code>evaluate</code> method,
 * if the <code>Target</code> is missing than this will return Indeterminate. This lets you
 * write your own custom matching routines for rules but lets evaluation proceed normally.
 * 
 * @param context the representation of the request
 * 
 * @return the result of trying to match this rule and the request
 */
public MatchResult match(EvaluationCtx context) {
    if (target == null) {
        ArrayList code = new ArrayList();
        code.add(Status.STATUS_PROCESSING_ERROR);
        Status status = new Status(code, "no target available for " + "matching a rule");

        return new MatchResult(MatchResult.INDETERMINATE, status);
    }

    return target.match(context);
}
 
Example #8
Source File: AttributeSelector.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Invokes the <code>AttributeFinder</code> used by the given <code>EvaluationCtx</code> to try
 * to resolve an attribute value. If the selector is defined with MustBePresent as true, then
 * failure to find a matching value will result in Indeterminate, otherwise it will result in an
 * empty bag. To support the basic selector functionality defined in the XACML specification,
 * use a finder that has only the <code>SelectorModule</code> as a module that supports selector
 * finding.
 *
 * @param context representation of the request to search
 *
 * @return a result containing a bag either empty because no values were found or containing at
 *         least one value, or status associated with an Indeterminate result
 */

public EvaluationResult evaluate(EvaluationCtx context) {
    // query the context
    EvaluationResult result = context.getAttribute(path, type, category,
                                                            contextSelectorId, xpathVersion);

    // see if we got anything
    if (!result.indeterminate()) {
        BagAttribute bag = (BagAttribute) (result.getAttributeValue());

        // see if it's an empty bag
        if (bag.isEmpty()) {
            // see if this is an error or not
            if (mustBePresent) {
                // this is an error
                if (logger.isDebugEnabled()) {
                    logger.debug("AttributeSelector failed to resolve a "
                            + "value for a required attribute: " + path);
                }

                ArrayList<String> code = new ArrayList<String>();
                code.add(Status.STATUS_MISSING_ATTRIBUTE);

                String message = "couldn't resolve XPath expression " + path
                        + " for type " + type.toString();
                return new EvaluationResult(new Status(code, message));
            } else {
                // return the empty bag
                return result;
            }
        } else {
            // return the values
            return result;
        }
    } else {
        // return the error
        return result;
    }
}
 
Example #9
Source File: AttributeSelector.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Invokes the <code>AttributeFinder</code> used by the given <code>EvaluationCtx</code> to try
 * to resolve an attribute value. If the selector is defined with MustBePresent as true, then
 * failure to find a matching value will result in Indeterminate, otherwise it will result in an
 * empty bag. To support the basic selector functionality defined in the XACML specification,
 * use a finder that has only the <code>SelectorModule</code> as a module that supports selector
 * finding.
 * 
 * @param context representation of the request to search
 * 
 * @return a result containing a bag either empty because no values were found or containing at
 *         least one value, or status associated with an Indeterminate result
 */
public EvaluationResult evaluate(EvaluationCtx context) {
    // query the context
    EvaluationResult result = context.getAttribute(contextPath, type, null, null, xpathVersion);

    // see if we got anything
    if (!result.indeterminate()) {
        BagAttribute bag = (BagAttribute) (result.getAttributeValue());

        // see if it's an empty bag
        if (bag.isEmpty()) {
            // see if this is an error or not
            if (mustBePresent) {
                // this is an error
                if (logger.isDebugEnabled()) {
                    logger.debug("AttributeSelector failed to resolve a "
                            + "value for a required attribute: " + contextPath);
                }

                ArrayList code = new ArrayList();
                code.add(Status.STATUS_MISSING_ATTRIBUTE);
                String message = "couldn't resolve XPath expression " + contextPath
                        + " for type " + type.toString();
                return new EvaluationResult(new Status(code, message));
            } else {
                // return the empty bag
                return result;
            }
        } else {
            // return the values
            return result;
        }
    } else {
        // return the error
        return result;
    }
}
 
Example #10
Source File: TargetSection.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Determines whether this <code>TargetSection</code> matches
 * the input request (whether it is applicable).
 * 
 * @param context the representation of the request
 *
 * @return the result of trying to match the target and the request
 */
public MatchResult match(EvaluationCtx context) {
    // if we apply to anything, then we always match
    if (matchGroups.isEmpty())
        return new MatchResult(MatchResult.MATCH);

    // there are specific matching elements, so prepare to iterate
    // through the list
    Status firstIndeterminateStatus = null;

    // in order for this section to match, one of the groups must match 
    for (TargetMatchGroup  group : matchGroups) {
        // get the next group and try matching it
        MatchResult result = group.match(context);

        // we only need one match, so if this matched, then we're done
        if (result.getResult() == MatchResult.MATCH)
            return result;

        // if we didn't match then it was either a NO_MATCH or
        // INDETERMINATE...in the second case, we need to remember
        // it happened, 'cause if we don't get a MATCH, then we'll
        // be returning INDETERMINATE
        if (result.getResult() == MatchResult.INDETERMINATE) {
            if (firstIndeterminateStatus == null)
                firstIndeterminateStatus = result.getStatus();
        }
    }

    // if we got here, then none of the sub-matches passed, so
    // we have to see if we got any INDETERMINATE cases
    if (firstIndeterminateStatus == null)
        return new MatchResult(MatchResult.NO_MATCH);
    else
        return new MatchResult(MatchResult.INDETERMINATE,
                               firstIndeterminateStatus);
}
 
Example #11
Source File: MatchResult.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor that creates a <code>MatchResult</code>, including Status data
 * 
 * @param result the applicable result
 * @param status the error information
 * 
 * @throws IllegalArgumentException if the input result isn't a valid value
 */
public MatchResult(int result, Status status) throws IllegalArgumentException {

    // check if input result is a valid value
    if ((result != MATCH) && (result != NO_MATCH) && (result != INDETERMINATE))
        throw new IllegalArgumentException("Input result is not a valid" + "value");

    this.result = result;
    this.status = status;
}
 
Example #12
Source File: FunctionBase.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Create an <code>EvaluationResult</code> that indicates a processing error with the specified
 * message. This method may be useful to subclasses.
 * 
 * @param message a description of the error (<code>null</code> if none)
 * @return the desired <code>EvaluationResult</code>
 */
protected static EvaluationResult makeProcessingError(String message) {
    // Build up the processing error Status.
    if (processingErrList == null) {
        String[] errStrings = { Status.STATUS_PROCESSING_ERROR };
        processingErrList = Arrays.asList(errStrings);
    }
    Status errStatus = new Status(processingErrList, message);
    EvaluationResult processingError = new EvaluationResult(errStatus);

    return processingError;
}
 
Example #13
Source File: URLStringCatFunction.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Evaluates the function given the input data. This function expects an
 * <code>AnyURIAttribute</code> followed by one or more <code>StringAttribute</code>s, and
 * returns an <code>AnyURIAttribute</code>.
 * 
 * @param inputs the input agrument list
 * @param context the representation of the request
 * 
 * @return the result of evaluation
 */
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {
	// Evaluate the arguments
	AttributeValue[] argValues = new AttributeValue[inputs.size()];
	EvaluationResult result = evalArgs(inputs, context, argValues);
	if (result != null)
		return result;

	// the first argument is always a URI
	String str = ((AnyURIAttribute) (argValues[0])).getValue().toString();

	// the remaining arguments are strings
	StringBuffer buffer = new StringBuffer(str);
	for (int i = 1; i < argValues.length; i++) {
		buffer.append(((StringAttribute) (argValues[i])).getValue());
	}

	// finally, try to convert the string back to a URI
	try {
		return new EvaluationResult(new AnyURIAttribute(new URI(str)));
	} catch (URISyntaxException use) {
		List code = new ArrayList();
		code.add(Status.STATUS_PROCESSING_ERROR);
		String message = NAME_URI_STRING_CONCATENATE + " didn't produce" + " a valid URI: "
				+ str;

		return new EvaluationResult(new Status(code, message));
	}
}
 
Example #14
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 #15
Source File: AnyOfSelection.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
     * Determines whether this <code>AnyOfSelection</code> matches the input request (whether it
     * is applicable).
     *
     * @param context the representation of the request
     *
     * @return the result of trying to match the group with the context
     */
    public MatchResult match(EvaluationCtx context) {

        // if we apply to anything, then we always match
//        if (allOfSelections.isEmpty())                   TODO 
//            return new MatchResult(MatchResult.MATCH);

        // there are specific matching elements, so prepare to iterate
        // through the list
        Status firstIndeterminateStatus = null;

        // in order for this section to match, one of the groups must match
        for (AllOfSelection group : allOfSelections) {
            // get the next group and try matching it
            MatchResult result = group.match(context);

            // we only need one match, so if this matched, then we're done
            if (result.getResult() == MatchResult.MATCH){
                return result;
            }
            // if we didn't match then it was either a NO_MATCH or
            // INDETERMINATE...in the second case, we need to remember
            // it happened, 'cause if we don't get a MATCH, then we'll
            // be returning INDETERMINATE
            if (result.getResult() == MatchResult.INDETERMINATE) {
                if (firstIndeterminateStatus == null)
                    firstIndeterminateStatus = result.getStatus();
            }
        }

        // if we got here, then none of the sub-matches passed, so
        // we have to see if we got any INDETERMINATE cases
        if (firstIndeterminateStatus == null){
            return new MatchResult(MatchResult.NO_MATCH);
        } else {
            return new MatchResult(MatchResult.INDETERMINATE,
                                   firstIndeterminateStatus);
        }
    }
 
Example #16
Source File: AllOfSelection.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 *
 * Determines whether this <code>AllOfSelection</code> matches the input request (whether it
 * is applicable).
 *
 * @param context the representation of the request
 *
 * @return the result of trying to match the group with the context
 */
public MatchResult match(EvaluationCtx context){

    // there are specific matching elements, so prepare to iterate
    // through the list
    Status firstIndeterminateStatus = null;
    MatchResult result;

    for (TargetMatch targetMatch : matches ) {
        result = targetMatch.match(context);
        if (result.getResult() == MatchResult.NO_MATCH){
            return result;
        }

        if (result.getResult() == MatchResult.INDETERMINATE){
            if(firstIndeterminateStatus == null){
                firstIndeterminateStatus = result.getStatus();
            }
        }
    }

    // if we got here, then none of the sub-matches passed, so
    // we have to see if we got any INDETERMINATE cases
    if (firstIndeterminateStatus == null)
        return new MatchResult(MatchResult.MATCH);
    else
        return new MatchResult(MatchResult.INDETERMINATE,
                               firstIndeterminateStatus);

}
 
Example #17
Source File: PolicyReference.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Given the input context sees whether or not the request matches this policy. This must be
 * called by combining algorithms before they evaluate a policy. This is also used in the
 * initial policy finding operation to determine which top-level policies might apply to the
 * request. If the policy is invalid or can't be retrieved, then a runtime exception is thrown.
 * 
 * @param context the representation of the request
 * 
 * @return the result of trying to match the policy and the request
 */
public MatchResult match(EvaluationCtx context) {
    try {
        return getTarget().match(context);
    } catch (ProcessingException pe) {
        // this means that we couldn't resolve the policy
        ArrayList code = new ArrayList();
        code.add(Status.STATUS_PROCESSING_ERROR);
        Status status = new Status(code, "couldn't resolve policy ref");
        return new MatchResult(MatchResult.INDETERMINATE, status);
    }
}
 
Example #18
Source File: MultipleCtxResult.java    From balana with Apache License 2.0 5 votes vote down vote up
public Status getStatus() {
    if(indeterminate){
        return status;
    } else {
        return null;
    }
}
 
Example #19
Source File: FileBasedPolicyFinderModule.java    From balana with Apache License 2.0 4 votes vote down vote up
@Override
public PolicyFinderResult findPolicy(EvaluationCtx context) {

    ArrayList<AbstractPolicy> selectedPolicies = new ArrayList<AbstractPolicy>();
    Set<Map.Entry<URI, AbstractPolicy>> entrySet = policies.entrySet();

    // iterate through all the policies we currently have loaded
    for (Map.Entry<URI, AbstractPolicy> entry : entrySet) {

        AbstractPolicy policy = entry.getValue();
        MatchResult match = policy.match(context);
        int result = match.getResult();

        // if target matching was indeterminate, then return the error
        if (result == MatchResult.INDETERMINATE)
            return new PolicyFinderResult(match.getStatus());

        // see if the target matched
        if (result == MatchResult.MATCH) {

            if ((combiningAlg == null) && (selectedPolicies.size() > 0)) {
                // we found a match before, so this is an error
                ArrayList<String> code = new ArrayList<String>();
                code.add(Status.STATUS_PROCESSING_ERROR);
                Status status = new Status(code, "too many applicable "
                        + "top-level policies");
                return new PolicyFinderResult(status);
            }

            // this is the first match we've found, so remember it
            selectedPolicies.add(policy);
        }
    }

    // no errors happened during the search, so now take the right
    // action based on how many policies we found
    switch (selectedPolicies.size()) {
        case 0:
            if (log.isDebugEnabled()) {
                log.debug("No matching XACML policy found");
            }
            return new PolicyFinderResult();
        case 1:
            return new PolicyFinderResult((selectedPolicies.get(0)));
        default:
            return new PolicyFinderResult(new PolicySet(null, combiningAlg, null, selectedPolicies));
    }
}
 
Example #20
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 #21
Source File: Result.java    From balana with Apache License 2.0 4 votes vote down vote up
public Result(int decision, Status status, List<ObligationResult> obligationResults,
              String resourceId) throws IllegalArgumentException {
    // version can be XACML 2.0,  1.1 or 1.0 But here we assume as XACML 2.0 as a common
    super(decision, status, obligationResults, null,  XACMLConstants.XACML_VERSION_2_0);
    this.resourceId = resourceId;
}
 
Example #22
Source File: Result.java    From balana with Apache License 2.0 4 votes vote down vote up
public Result(int decision, Status status, List<ObligationResult> obligationResults)
                                                            throws IllegalArgumentException {
    // version can be XACML 2.0,  1.1 or 1.0 But here we assume as XACML 2.0 as a common
    super(decision, status, obligationResults, null,  XACMLConstants.XACML_VERSION_2_0);
}
 
Example #23
Source File: Result.java    From balana with Apache License 2.0 4 votes vote down vote up
public Result(int decision, Status status){
    // version can be XACML 2.0,  1.1 or 1.0 But here we assume as XACML 2.0 as a common
    super(decision, status, XACMLConstants.XACML_VERSION_2_0);
}
 
Example #24
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 #25
Source File: Result.java    From balana with Apache License 2.0 4 votes vote down vote up
public Result(int decision, Status status){
    super(decision, status, XACMLConstants.XACML_VERSION_3_0);
}
 
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: CurrentEnvModule.java    From balana with Apache License 2.0 4 votes vote down vote up
/**
 * Private helper that generates a new processing error status and includes the given string.
 */
private EvaluationResult makeProcessingError(String message) {
    ArrayList code = new ArrayList();
    code.add(Status.STATUS_PROCESSING_ERROR);
    return new EvaluationResult(new Status(code, message));
}
 
Example #29
Source File: DefaultPolicyCollection.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
/**
 * Attempts to retrieve a policy based on the given context. If multiple policies match then
 * this will either throw an exception or wrap the policies under a new PolicySet (depending on
 * how this instance was constructed). If no policies match, then this will return null. See the
 * comment in the class header about how this behaves when multiple versions of the same policy
 * exist.
 *
 * @param context
 * @return
 * @throws EntitlementException
 */
public AbstractPolicy getEffectivePolicy(EvaluationCtx context) throws EntitlementException {
    // setup a list of matching policies
    ArrayList<AbstractPolicy> list = new ArrayList<AbstractPolicy>();
    // get an iterator over all the identifiers
    Iterator<TreeSet<AbstractPolicy>> it = policies.values().iterator();

    while (it.hasNext()) {
        // for each identifier, get only the most recent policy
        AbstractPolicy policy = it.next().first();

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

        // if there was an error, we stop right away
        if (result == MatchResult.INDETERMINATE) {
            log.error(match.getStatus().getMessage());
            throw new EntitlementException(match.getStatus().getMessage());
        }

        // if we matched, we keep track of the matching policy...
        if (result == MatchResult.MATCH) {
            // ...first checking if this is the first match and if
            // we automatically nest policies

            if (log.isDebugEnabled()) {
                log.debug("Matching XACML policy found " + policy.getId().toString());
            }

            if ((combiningAlg == null) && (list.size() > 0)) {
                ArrayList<String> code = new ArrayList<String>();
                code.add(Status.STATUS_PROCESSING_ERROR);
                Status status = new Status(code, "too many applicable top-level policies");
                //throw new EntitlementException(status);     // TODO
            }

            list.add(policy);
        }
    }

    // no errors happened during the search, so now take the right
    // action based on how many policies we found
    switch (list.size()) {
        case 0:
            if (log.isDebugEnabled()) {
                log.debug("No matching XACML policy found");
            }
            return null;
        case 1:
            return ((AbstractPolicy) (list.get(0)));
        default:
            return new PolicySet(parentId, combiningAlg, null, list);
    }
}
 
Example #30
Source File: PolicyFinder.java    From balana with Apache License 2.0 4 votes vote down vote up
/**
 * Finds a policy based on an id reference. This may involve using the reference as indexing
 * data to lookup a policy. This will always do a Target match to make sure that the given
 * policy applies. If more than one applicable policy is found, this will return an error.
 * 
 * @param idReference the identifier used to resolve a policy
 * @param type type of reference (policy or policySet) as identified by the fields in
 *            <code>PolicyReference</code>
 * @param constraints any optional constraints on the version of the referenced policy
 * @param parentMetaData the meta-data from the parent policy, which provides XACML version,
 *            factories, etc.
 * 
 * @return the result of trying to find an applicable policy
 * 
 * @throws IllegalArgumentException if <code>type</code> is invalid
 */
public PolicyFinderResult findPolicy(URI idReference, int type, VersionConstraints constraints,
        PolicyMetaData parentMetaData) throws IllegalArgumentException {
    PolicyFinderResult result = null;
    Iterator it = referenceModules.iterator();

    if ((type != PolicyReference.POLICY_REFERENCE)
            && (type != PolicyReference.POLICYSET_REFERENCE))
        throw new IllegalArgumentException("Unknown reference type");

    // look through all of the modules
    while (it.hasNext()) {
        PolicyFinderModule module = (PolicyFinderModule) (it.next());
        PolicyFinderResult newResult = module.findPolicy(idReference, type, constraints,
                parentMetaData);

        // if there was an error, we stop right away
        if (newResult.indeterminate()) {
            logger.error("An error occured while trying to find the " + "referenced policy "
                    + idReference.toString() + ": " + newResult.getStatus().getMessage());

            return newResult;
        }

        // if we found a policy...
        if (!newResult.notApplicable()) {
            // ...if we already had found a policy, this is an error...
            if (result != null) {
                logger.error("More than one policy applies for the " + "reference: "
                        + idReference.toString());
                ArrayList code = new ArrayList();
                code.add(Status.STATUS_PROCESSING_ERROR);
                Status status = new Status(code, "too many applicable " + "top-level policies");
                return new PolicyFinderResult(status);
            }

            // ...otherwise we remember the result
            result = newResult;
        }
    }

    // if we got here then we didn't have any errors, so the only
    // question is whether or not we found anything
    if (result != null) {
        return result;
    } else {
        logger.debug("No policies were resolved for the reference: " + idReference.toString());
        return new PolicyFinderResult();
    }
}