org.wso2.balana.cond.EvaluationResult Java Examples

The following examples show how to use org.wso2.balana.cond.EvaluationResult. 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: 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 #2
Source File: XACML2EvaluationCtx.java    From balana with Apache License 2.0 6 votes vote down vote up
public EvaluationResult getAttribute(URI type, URI id, String issuer, URI category) {

        if(XACMLConstants.SUBJECT_CATEGORY.equals(category.toString())){
            return getSubjectAttribute(type, id, category, issuer);
        } else if(XACMLConstants.RESOURCE_CATEGORY.equals(category.toString())){
            return getResourceAttribute(type, id, category, issuer);
        } else if(XACMLConstants.ACTION_CATEGORY.equals(category.toString())){
            return getActionAttribute(type, id, category, issuer);
        } else if(XACMLConstants.ENT_CATEGORY.equals(category.toString())){
            return getEnvironmentAttribute(type, id, category, issuer);
        } else {
            ArrayList<String> code = new ArrayList<String>();
            code.add(Status.STATUS_PROCESSING_ERROR);                                                                            ;
            Status status = new Status(code);
            return  new EvaluationResult(status);
        }
    }
 
Example #3
Source File: SampleAttributeFinderModule.java    From balana with Apache License 2.0 6 votes vote down vote up
@Override
public EvaluationResult findAttribute(URI attributeType, URI attributeId, String issuer,
                                      URI category, EvaluationCtx context) {
    String roleName = null;
    List<AttributeValue> attributeValues = new ArrayList<AttributeValue>();
    EvaluationResult result = context.getAttribute(attributeType, defaultSubjectId, issuer, category);

    if(result != null && result.getAttributeValue() != null && result.getAttributeValue().isBag()){

        BagAttribute bagAttribute = (BagAttribute) result.getAttributeValue();
        if(bagAttribute.size() > 0){
            String userName = ((AttributeValue) bagAttribute.iterator().next()).encode();
            roleName = findRole(userName);
        }
    }
    if (roleName != null) {
        attributeValues.add(new StringAttribute(roleName));
    }
    return new EvaluationResult(new BagAttribute(attributeType, attributeValues));
}
 
Example #4
Source File: SampleAttributeFinderModule.java    From balana with Apache License 2.0 6 votes vote down vote up
@Override
public EvaluationResult findAttribute(URI attributeType, URI attributeId, String issuer,
                                                        URI category, EvaluationCtx context) {
    String roleName = null;
    List<AttributeValue> attributeValues = new ArrayList<AttributeValue>();

    EvaluationResult result = context.getAttribute(attributeType, defaultSubjectId, issuer, category);
    if(result != null && result.getAttributeValue() != null && result.getAttributeValue().isBag()){
        BagAttribute bagAttribute = (BagAttribute) result.getAttributeValue();
        if(bagAttribute.size() > 0){
            String userName = ((AttributeValue) bagAttribute.iterator().next()).encode();
            roleName = findRole(userName);
        }
    }

    if (roleName != null) {
        attributeValues.add(new StringAttribute(roleName));
    }

    return new EvaluationResult(new BagAttribute(attributeType, attributeValues));
}
 
Example #5
Source File: SampleAttributeFinderModule.java    From balana with Apache License 2.0 6 votes vote down vote up
@Override
public EvaluationResult findAttribute(URI attributeType, URI attributeId, String issuer,
                                                        URI category, EvaluationCtx context) {
    String roleName = null;
    List<AttributeValue> attributeValues = new ArrayList<AttributeValue>();

    EvaluationResult result = context.getAttribute(attributeType, defaultSubjectId, issuer, category);
    if(result != null && result.getAttributeValue() != null && result.getAttributeValue().isBag()){
        BagAttribute bagAttribute = (BagAttribute) result.getAttributeValue();
        if(bagAttribute.size() > 0){
            String userName = ((AttributeValue) bagAttribute.iterator().next()).encode();
            roleName = findRole(userName);
        }
    }

    if (roleName != null) {
        attributeValues.add(new StringAttribute(roleName));
    }

    return new EvaluationResult(new BagAttribute(attributeType, attributeValues));
}
 
Example #6
Source File: SampleAttributeFinderModule.java    From balana with Apache License 2.0 6 votes vote down vote up
@Override
public EvaluationResult findAttribute(URI attributeType, URI attributeId, String issuer,
                                                        URI category, EvaluationCtx context) {
    String roleName = null;
    List<AttributeValue> attributeValues = new ArrayList<AttributeValue>();

    EvaluationResult result = context.getAttribute(attributeType, defaultSubjectId, issuer, category);
    if(result != null && result.getAttributeValue() != null && result.getAttributeValue().isBag()){
        BagAttribute bagAttribute = (BagAttribute) result.getAttributeValue();
        if(bagAttribute.size() > 0){
            String userName = ((AttributeValue) bagAttribute.iterator().next()).encode();
            roleName = findRole(userName);
        }
    }

    if (roleName != null) {
        attributeValues.add(new StringAttribute(roleName));
    }

    return new EvaluationResult(new BagAttribute(attributeType, attributeValues));
}
 
Example #7
Source File: TargetMatch.java    From balana with Apache License 2.0 6 votes vote down vote up
/**
 * Private helper that evaluates an individual match.
 *
 * @param inputs  <code>List</code> of <code>Evaluatable</code>
 * @param context  <code>EvaluationCtx</code>
 * @return  match result as <code>MatchResult</code>
 */
private MatchResult evaluateMatch(List inputs, EvaluationCtx context) {
    // first off, evaluate the function
    EvaluationResult result = function.evaluate(inputs, context);

    // if it was indeterminate, then that's what we return immediately
    if (result.indeterminate())
        return new MatchResult(MatchResult.INDETERMINATE, result.getStatus());

    // otherwise, we figure out if it was a match
    BooleanAttribute bool = (BooleanAttribute) (result.getAttributeValue());

    if (bool.getValue())
        return new MatchResult(MatchResult.MATCH);
    else
        return new MatchResult(MatchResult.NO_MATCH);
}
 
Example #8
Source File: XACML3HigherOrderFunction.java    From balana with Apache License 2.0 6 votes vote down vote up
private EvaluationResult getEvaluationResult(EvaluationCtx context, Function function, AttributeValue val1,
                                             AttributeValue val2, boolean isAllFunction) {

    List<Evaluatable> params = new ArrayList<>();
    params.add(val1);
    params.add(val2);
    EvaluationResult result = function.evaluate(params, context);

    if (result.indeterminate()) {
        return result;
    }

    BooleanAttribute bool = (BooleanAttribute) (result.getAttributeValue());
    if (bool.getValue() != isAllFunction) {
        return result;
    }
    return null;
}
 
Example #9
Source File: XACML3EvaluationCtx.java    From balana with Apache License 2.0 6 votes vote down vote up
public EvaluationResult getAttribute(URI type, URI id, String issuer, URI category) {

        List<AttributeValue> attributeValues = new ArrayList<AttributeValue>();
        List<Attributes> attributesSet = mapAttributes.get(category.toString());
        if(attributesSet != null && attributesSet.size() > 0){
            Set<Attribute> attributeSet  = attributesSet.get(0).getAttributes();
            for(Attribute attribute : attributeSet) {
                if(attribute.getId().toString().equals(id.toString())
                        && attribute.getType().toString().equals(type.toString())
                        && (issuer == null || issuer.equals(attribute.getIssuer()))
                        && attribute.getValue() != null){
                    List<AttributeValue> attributeValueList = attribute.getValues();
                    for (AttributeValue attributeVal : attributeValueList) {
                    	attributeValues.add(attributeVal);
                    }
                }
            }
        }
        if (attributeValues.isEmpty()) {
            return callHelper(type, id, issuer, category);
        }

        // if we got here, then we found at least one useful AttributeValue
        return new EvaluationResult(new BagAttribute(type, attributeValues));
    }
 
Example #10
Source File: CurrentEnvModule.java    From balana with Apache License 2.0 6 votes vote down vote up
/**
 * Used to get the current time, date, or dateTime. If one of those values isn't being asked
 * for, or if the types are wrong, then an empty bag is returned.
 * 
 * @param attributeType the datatype of the attributes to find, which must be time, date, or
 *            dateTime for this module to resolve a value
 * @param attributeId the identifier of the attributes to find, which must be one of the three
 *            ENVIRONMENT_* fields for this module to resolve a value
 * @param issuer the issuer of the attributes, or null if unspecified
 * @param category the category of the attribute 
 * @param context the representation of the request data
 * 
 * @return the result of attribute retrieval, which will be a bag with a single attribute, an
 *         empty bag, or an error
 */
public EvaluationResult findAttribute(URI attributeType, URI attributeId, String issuer,
        URI category, EvaluationCtx context) {
    // we only know about environment attributes
    if (!XACMLConstants.ENT_CATEGORY.equals(category.toString())){
        return new EvaluationResult(BagAttribute.createEmptyBag(attributeType));
    }
    // figure out which attribute we're looking for
    String attrName = attributeId.toString();

    if (attrName.equals(ENVIRONMENT_CURRENT_TIME)) {
        return handleTime(attributeType, issuer, context);
    } else if (attrName.equals(ENVIRONMENT_CURRENT_DATE)) {
        return handleDate(attributeType, issuer, context);
    } else if (attrName.equals(ENVIRONMENT_CURRENT_DATETIME)) {
        return handleDateTime(attributeType, issuer, context);
    }

    // if we got here, then it's an attribute that we don't know
    return new EvaluationResult(BagAttribute.createEmptyBag(attributeType));
}
 
Example #11
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 #12
Source File: XACML3HigherOrderFunction.java    From balana with Apache License 2.0 5 votes vote down vote up
private EvaluationResult anyAndAllHelper(EvaluationCtx context, Function function, List<AttributeValue> values,
                                         BagAttribute bag, boolean isAllFunction) {

    Iterator it = bag.iterator();
    while (it.hasNext()) {
        AttributeValue bagValue = (AttributeValue) (it.next());
        for (AttributeValue value : values) {
            EvaluationResult result = getEvaluationResult(context, function, value, bagValue, isAllFunction);
            if (result != null) {
                return result;
            }
        }
    }
    return new EvaluationResult(BooleanAttribute.getInstance(isAllFunction));
}
 
Example #13
Source File: DefaultAttributeFinder.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * This method is introduced in order to check whether the user is local or federated. If it is a
 * federated user, obtaining user attributes from userstore will be prevented.
 *
 * @param attributeType The type of the required attribute.
 * @param attributeId   The unique id of the required attribute.
 * @param category      The category of the required attribute.
 * @param issuer        The attribute issuer.
 * @param evaluationCtx The evaluation context object.
 * @return return the set of values for the required attribute.
 * @throws Exception throws if fails.
 */
@Override
public Set<String> getAttributeValues(URI attributeType, URI attributeId, URI category,
                                      String issuer, EvaluationCtx evaluationCtx) throws Exception {

    Set<String> values = null;
    EvaluationResult userType = evaluationCtx.getAttribute(new URI(StringAttribute.identifier), new URI(
            PDPConstants.USER_TYPE_ID), issuer, new URI(PDPConstants.USER_CATEGORY));
    String userTypeId = null;
    if (userType != null && userType.getAttributeValue() != null && userType.getAttributeValue().isBag()) {
        BagAttribute bagAttribute = (BagAttribute) userType.getAttributeValue();
        if (bagAttribute.size() > 0) {
            userTypeId = ((AttributeValue) bagAttribute.iterator().next()).encode();
            if (log.isDebugEnabled()) {
                log.debug(String.format("The user type of the user is %s", userTypeId));
            }
        }
    }

    if (!StringUtils.equalsIgnoreCase(userTypeId, FEDERATED_USER_DOMAIN)) {
        // If the user is not a federated user, user attributes should be be populated from local userstore.
        values = super.getAttributeValues(attributeType, attributeId, category, issuer, evaluationCtx);
    } else if (mapFederatedUsersToLocal) {
        // If the user is federated and the MapFederatedToLocal config is enabled, then populate user attributes
        // from userstore.
        values = super.getAttributeValues(attributeType, attributeId, category, issuer, evaluationCtx);
    }
    return values;
}
 
Example #14
Source File: CurrentEnvModule.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Private helper that makes a bag containing only the given attribute.
 */
private EvaluationResult makeBag(AttributeValue attribute) {
    List<AttributeValue> set = new ArrayList<AttributeValue>();
    set.add(attribute);

    BagAttribute bag = new BagAttribute(attribute.getType(), set);

    return new EvaluationResult(bag);
}
 
Example #15
Source File: CurrentEnvModule.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Handles requests for the current Time.
 */
private EvaluationResult handleTime(URI type, String issuer, EvaluationCtx context) {
    // make sure they're asking for a time attribute
    if (!type.toString().equals(TimeAttribute.identifier))
        return new EvaluationResult(BagAttribute.createEmptyBag(type));

    // get the value from the context
    return makeBag(context.getCurrentTime());
}
 
Example #16
Source File: CurrentEnvModule.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Handles requests for the current Date.
 */
private EvaluationResult handleDate(URI type, String issuer, EvaluationCtx context) {
    // make sure they're asking for a date attribute
    if (!type.toString().equals(DateAttribute.identifier))
        return new EvaluationResult(BagAttribute.createEmptyBag(type));

    // get the value from the context
    return makeBag(context.getCurrentDate());
}
 
Example #17
Source File: CurrentEnvModule.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Handles requests for the current DateTime.
 */
private EvaluationResult handleDateTime(URI type, String issuer, EvaluationCtx context) {
    // make sure they're asking for a dateTime attribute
    if (!type.toString().equals(DateTimeAttribute.identifier))
        return new EvaluationResult(BagAttribute.createEmptyBag(type));

    // get the value from the context
    return makeBag(context.getCurrentDateTime());
}
 
Example #18
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 #19
Source File: BasicEvaluationCtx.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the attribute value(s) retrieved using the given XPath expression.
 *
 * @param path the XPath expression to search
 * @param type the type of the attribute value(s) to find
 * @param category the category the attribute value(s) must be in
 * @param contextSelector the selector to find the context to apply XPath expression
 *                       if this is null, applied for default content
 * @param xpathVersion the version of XPath to use
 *
 * @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 getAttribute(String path, URI type, URI category,
                                     URI contextSelector, String xpathVersion){

    if (pdpConfig.getAttributeFinder() != null) {
        return pdpConfig.getAttributeFinder().findAttribute(path, type, this,
                                    xpathVersion);
    } else {
        logger.warn("Context tried to invoke AttributeFinder but was " +
                       "not configured with one");

        return new EvaluationResult(BagAttribute.createEmptyBag(type));
    }
}
 
Example #20
Source File: BasicEvaluationCtx.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Private helper that calls the finder if it's non-null, or else returns an empty bag
 *
 * @param type the type of the attribute value(s) to find
 * @param id the id of the attribute value(s) to find
 * @param issuer the issuer of the attribute value(s) to find or null
 * @param category the category the attribute value(s) must be in
 *
 * @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
 */
protected EvaluationResult callHelper(URI type, URI id, String issuer, URI category) {
    if (pdpConfig.getAttributeFinder() != null) {
        return pdpConfig.getAttributeFinder().findAttribute(type, id, issuer, category, this);
    } else {
        if (logger.isWarnEnabled()) {
            logger.warn("Context tried to invoke AttributeFinder but was "
                    + "not configured with one");
        }

        return new EvaluationResult(BagAttribute.createEmptyBag(type));
    }
}
 
Example #21
Source File: SubStringFunction.java    From balana with Apache License 2.0 5 votes vote down vote up
public EvaluationResult evaluate(List<Evaluatable> inputs, EvaluationCtx context) {

        // Evaluate the arguments
        AttributeValue[] argValues = new AttributeValue[inputs.size()];
        EvaluationResult result = evalArgs(inputs, context, argValues);
        if (result != null) {
            return result;
        }

        String processedString = argValues[0].encode().substring(Integer.parseInt(argValues[1].encode()),
                                                        Integer.parseInt(argValues[2].encode()));

        return new EvaluationResult(new StringAttribute(processedString));
    }
 
Example #22
Source File: StringComparingFunction.java    From balana with Apache License 2.0 5 votes vote down vote up
public EvaluationResult evaluate(List<Evaluatable> inputs, EvaluationCtx context) {

        // Evaluate the arguments
        AttributeValue[] argValues = new AttributeValue[inputs.size()];
        EvaluationResult result = evalArgs(inputs, context, argValues);
        if (result != null) {
            return result;
        }

        int id = getFunctionId();

        if(id == ID_STRING_START_WITH || id == ID_ANY_URI_START_WITH){
            // do not want to check for anyURI and String data types. As both attribute values would
            // returns String data type after encode() is done,
            return EvaluationResult.getInstance(argValues[1].encode().
                                                            startsWith(argValues[0].encode()));
        } else if(id == ID_STRING_ENDS_WITH || id == ID_ANY_URI_ENDS_WITH){
            // do not want to check for anyURI and String data types. As both attribute values would
            // returns String data type after encode() is done,
            return EvaluationResult.getInstance(argValues[1].encode().
                                                            endsWith(argValues[0].encode()));
        } else {
            // do not want to check for anyURI and String data types. As both attribute values would
            // returns String data type after encode() is done,
            return EvaluationResult.getInstance(argValues[1].encode().
                                                            contains(argValues[0].encode()));
        }
    }
 
Example #23
Source File: StringCreationFunction.java    From balana with Apache License 2.0 5 votes vote down vote up
public EvaluationResult evaluate(List<Evaluatable> inputs, EvaluationCtx context) {
    // Evaluate the arguments
    AttributeValue[] argValues = new AttributeValue[inputs.size()];
    EvaluationResult result = evalArgs(inputs, context, argValues);
    if (result != null){
        return result;
    }

    return new EvaluationResult(new StringAttribute(argValues[0].encode()));
}
 
Example #24
Source File: XACML2EvaluationCtx.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Returns attribute value(s) from the subject section of the request.
 *
 * @param type     the type of the attribute value(s) to find
 * @param id       the id of the attribute value(s) to find
 * @param issuer   the issuer of the attribute value(s) to find or null
 * @param category the category the attribute value(s) must be in
 * @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 getSubjectAttribute(URI type, URI id, URI category, String issuer) {
    // This is the same as the other three lookups except that this
    // has an extra level of indirection that needs to be handled first
    Map map = (Map) (subjectMap.get(category));

    if (map == null) {
        // the request didn't have that category, so we should try asking
        // the attribute finder
        return callHelper(type, id, issuer, category);
    }

    return getGenericAttributes(type, id, category, issuer, map);
}
 
Example #25
Source File: XACML3EvaluationCtx.java    From balana with Apache License 2.0 4 votes vote down vote up
public EvaluationResult getAttribute(String path, URI type, URI category,
                                     URI contextSelector, String xpathVersion){

    if(pdpConfig.getAttributeFinder() == null){

        logger.warn("Context tried to invoke AttributeFinder but was " +
                       "not configured with one");
        return new EvaluationResult(BagAttribute.createEmptyBag(type));
    }

    List<Attributes> attributesSet = null;

    if(category != null){
        attributesSet = mapAttributes.get(category.toString());
    }

    if(attributesSet != null && attributesSet.size() > 0){
        Attributes attributes  = attributesSet.get(0);
        Object content = attributes.getContent();
        if(content instanceof Node){
            Node root = (Node) content;
            if(contextSelector != null && contextSelector.toString().trim().length() > 0){
                for(Attribute attribute : attributes.getAttributes()) {
                    if(attribute.getId().equals(contextSelector)){
                        List<AttributeValue> values = attribute.getValues();
                        for(AttributeValue value : values){
                            if(value instanceof XPathAttribute){
                                XPathAttribute xPathAttribute = (XPathAttribute)value;
                                if(xPathAttribute.getXPathCategory().
                                                                equals(category.toString())){
                                    return pdpConfig.getAttributeFinder().findAttribute(path,
                                                        xPathAttribute.getValue(), type,
                                                        root, this, xpathVersion);
                                }
                            }
                        }
                    }
                }
            } else {
                return pdpConfig.getAttributeFinder().findAttribute(path, null, type,
                                                     root, this, xpathVersion);
            }
        }
    }

    return new EvaluationResult(BagAttribute.createEmptyBag(type));
}
 
Example #26
Source File: AbstractPIPResourceFinder.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
@Override
public Set<String> findDescendantResources(String parentResourceId, EvaluationCtx context)
        throws Exception {

    EvaluationResult environment;
    String environmentId = null;
    Set<String> resourceNames = null;

    NodeList children = context.getRequestRoot().getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node child = children.item(i);
        if (child != null) {
            if (PDPConstants.ENVIRONMENT_ELEMENT.equals(child.getLocalName())) {
                if (child.getChildNodes() != null && child.getChildNodes().getLength() > 0) {
                    environment = context.getAttribute(new URI(StringAttribute.identifier),
                            new URI(PDPConstants.ENVIRONMENT_ID_DEFAULT), null,
                            new URI(XACMLConstants.ENT_CATEGORY));
                    if (environment != null && environment.getAttributeValue() != null &&
                            environment.getAttributeValue().isBag()) {
                        BagAttribute attr = (BagAttribute) environment.getAttributeValue();
                        environmentId = ((AttributeValue) attr.iterator().next()).encode();
                    }
                }
            }
        }
    }

    if (isAbstractResourceCacheEnabled) {
        IdentityCacheKey cacheKey;
        String key = PDPConstants.RESOURCE_DESCENDANTS + parentResourceId +
                (environmentId != null ? environmentId : "");
        tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
        cacheKey = new IdentityCacheKey(tenantId, key);
        IdentityCacheEntry cacheEntry = (IdentityCacheEntry) abstractResourceCache.getValueFromCache(cacheKey);
        if (cacheEntry != null) {
            String[] values = cacheEntry.getCacheEntryArray();
            resourceNames = new HashSet<String>(Arrays.asList(values));
            if (log.isDebugEnabled()) {
                log.debug("Carbon Resource Cache Hit");
            }
        }

        if (resourceNames != null) {
            resourceNames = findDescendantResources(parentResourceId, environmentId);
            if (log.isDebugEnabled()) {
                log.debug("Carbon Resource Cache Miss");
            }
            if (resourceNames != null && !resourceNames.isEmpty()) {
                cacheEntry = new IdentityCacheEntry(resourceNames.toArray(new String[resourceNames.size()]));
                abstractResourceCache.addToCache(cacheKey, cacheEntry);
            }
        }
    } else {
        resourceNames = findDescendantResources(parentResourceId, environmentId);
    }

    return resourceNames;
}
 
Example #27
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 #28
Source File: XACML2EvaluationCtx.java    From balana with Apache License 2.0 4 votes vote down vote up
/**
 * Helper function for the resource, action and environment methods to get an attribute.
 */
private EvaluationResult getGenericAttributes(URI type, URI id, URI category, String issuer,
                                                                                    Map map) {
    // try to find the id
    Set attrSet = (Set) (map.get(id.toString()));
    if (attrSet == null) {
        // the request didn't have an attribute with that id, so we should
        // try asking the attribute finder
        return callHelper(type, id, issuer, category);
    }

    // now go through each, considering each Attribute object
    List<AttributeValue> attributes = new ArrayList<AttributeValue>();
    Iterator it = attrSet.iterator();

    while (it.hasNext()) {
        Attribute attr = (Attribute) (it.next());

        // make sure the type and issuer are correct
        if ((attr.getType().equals(type))
                && ((issuer == null) || ((attr.getIssuer() != null) && (attr.getIssuer()
                .equals(issuer))))) {

            // if we got here, then we found a match, so we want to pull
            // out the values and put them in out list
            attributes.add(attr.getValue());
        }
    }

    // see if we found any acceptable attributes
    if (attributes.size() == 0) {
        // we failed to find any that matched the type/issuer, or all the
        // Attribute types were empty...so ask the finder
        if (logger.isDebugEnabled())
            logger.debug("Attribute not in request: " + id.toString()
                    + " ... querying AttributeFinder");

        return callHelper(type, id, issuer, category);
    }

    // if we got here, then we found at least one useful AttributeValue
    return new EvaluationResult(new BagAttribute(type, attributes));
}
 
Example #29
Source File: AttributeDesignator.java    From balana with Apache License 2.0 4 votes vote down vote up
/**
 * Evaluates the pre-assigned meta-data against the given context, trying to find some matching
 * values.
 *
 * @param context the representation of the request
 * @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) {
    EvaluationResult result = null;

    // look in  attribute values
    result = context.getAttribute(type, id, issuer, category);

    // if the lookup was indeterminate, then we return immediately
    if (result.indeterminate()){
        return result;
    }
    BagAttribute bag = (BagAttribute) (result.getAttributeValue());

    if (bag.isEmpty()) {
        // if it's empty, this may be an error
        if (mustBePresent) {
            if (logger.isDebugEnabled()) {
                logger.debug("AttributeDesignator failed to resolve a "
                        + "value for a required attribute: " + id.toString());
            }

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

            ArrayList<MissingAttributeDetail> missingAttributes = new ArrayList<MissingAttributeDetail>();
            MissingAttributeDetail missingAttribute = new MissingAttributeDetail(id, type,
                                    category, issuer, null, XACMLConstants.XACML_VERSION_3_0);
            missingAttributes.add(missingAttribute);
            StatusDetail detail = new StatusDetail(missingAttributes);

            String message = "Couldn't find AttributeDesignator attribute";

            // Note that there is a bug in the XACML spec. You can't
            // specify an identifier without specifying acceptable
            // values. Until this is fixed, this code will only
            // return the status code, and not any hints about what
            // was missing

            /*
            * List attrs = new ArrayList(); attrs.add(new Attribute(id, ((issuer == null) ?
            * null : issuer.toString()), null, null)); StatusDetail detail = new
            * StatusDetail(attrs);
            */

            return new EvaluationResult(new Status(code, message, detail));
        }
    }

    // if we got here the bag wasn't empty, or mustBePresent was false,
    // so we just return the result
    return result;
}
 
Example #30
Source File: XACML3HigherOrderFunction.java    From balana with Apache License 2.0 4 votes vote down vote up
private EvaluationResult anyOfAny(EvaluationCtx context, Function function, List<AttributeValue> args,
                                  List<BagAttribute> bagArgs) {

    // The expression SHALL be evaluated as if the function named in the <Function> argument was applied
    // between every tuple of the cross product on all bags and the primitive values, and the results were
    // combined using “urn:oasis:names:tc:xacml:1.0:function:or”

    EvaluationResult result = new EvaluationResult(BooleanAttribute.getInstance(false));
    if (!args.isEmpty()) {
        for (int i = 0; i < args.size() - 1; i++) {
            AttributeValue value = args.get(i);
            List<AttributeValue> bagValue = new ArrayList<>();
            bagValue.add(value);
            BagAttribute bagArg = new BagAttribute(value.getType(), bagValue);
            result = anyAndAllHelper(context, function, args.subList(i + 1, args.size()), bagArg, false);
            if (result.indeterminate() || ((BooleanAttribute) (result.getAttributeValue())).getValue()) {
                return result;
            }
        }
        return new EvaluationResult(BooleanAttribute.getInstance(false));
    }
    if (!bagArgs.isEmpty()) {
        for (int i = 0; i < bagArgs.size(); i++) {
            for (int j = i + 1; j < bagArgs.size(); j++) {
                Iterator iIterator = bagArgs.get(i).iterator();
                while (iIterator.hasNext()) {
                    AttributeValue iValue = (AttributeValue) (iIterator.next());
                    Iterator jIterator = bagArgs.get(j).iterator();
                    while (jIterator.hasNext()) {
                        AttributeValue jValue = (AttributeValue) (jIterator.next());
                        result = getEvaluationResult(context, function, jValue, iValue, false);
                        if (result != null && (result.indeterminate() ||
                                ((BooleanAttribute) (result.getAttributeValue())).getValue())) {
                            return result;
                        }
                    }
                }
            }
        }
        return new EvaluationResult(BooleanAttribute.getInstance(false));
    }
    return null;
}