repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/ProcessingException.java
/* * @(#)ProcessingException.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana; /** * Runtime exception that's thrown if any unexpected error occurs. This could appear, for example, * if you try to match a referernced policy that can't be resolved. * * @since 1.0 * @author Seth Proctor */ public class ProcessingException extends RuntimeException { /** * Constructs a new <code>ProcessingException</code> with no message or cause. */ public ProcessingException() { } /** * Constructs a new <code>ProcessingException</code> with a message, but no cause. The message * is saved for later retrieval by the {@link java.lang#Throwable.getMessage() * Throwable.getMessage()} method. * * @param message the detail message (<code>null</code> if nonexistent or unknown) */ public ProcessingException(String message) { super(message); } /** * Constructs a new <code>ProcessingException</code> with a cause, but no message. The cause is * saved for later retrieval by the {@link java.lang#Throwable.getCause() Throwable.getCause()} * method. * * @param cause the cause (<code>null</code> if nonexistent or unknown) */ public ProcessingException(Throwable cause) { super(cause); } /** * Constructs a new <code>ProcessingException</code> with a message and a cause. The message and * cause are saved for later retrieval by the {@link java.lang#Throwable.getMessage() * Throwable.getMessage()} and {@link java.lang#Throwable.getCause() Throwable.getCause()} * methods. * * @param message the detail message (<code>null</code> if nonexistent or unknown) * @param cause the cause (<code>null</code> if nonexistent or unknown) */ public ProcessingException(String message, Throwable cause) { super(message, cause); } }
3,674
39.833333
100
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/Indenter.java
/* * @(#)Indenter.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana; import java.util.Arrays; /** * Provides flexible indenting for XML encoding. This class generates strings of spaces to be * prepended to lines of XML. The strings are formed according to a specified indent width and the * given depth. * * @since 1.0 * @author Marco Barreno * @author Seth Proctor */ public class Indenter { /** * The default indentation width */ public static final int DEFAULT_WIDTH = 2; // The width of one indentation level private int width; // the current depth private int depth; /** * Constructs an <code>Indenter</code> with the default indent width. */ public Indenter() { this(DEFAULT_WIDTH); } /** * Constructs an <code>Indenter</code> with a user-supplied indent width. * * @param userWidth the number of spaces to use for each indentation level */ public Indenter(int userWidth) { width = userWidth; depth = 0; } /** * Move in one width. */ public void in() { depth += width; } /** * Move out one width. */ public void out() { depth -= width; } /** * Create a <code>String</code> of spaces for indentation based on the current depth. * * @return an indent string to prepend to lines of XML */ public String makeString() { // Return quickly if no indenting if (depth <= 0) { return ""; } // Make a char array and fill it with spaces char[] array = new char[depth]; Arrays.fill(array, ' '); // Now return a string built from that char array return new String(array); } }
3,346
28.619469
98
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/DefaultNamespaceContext.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana; import javax.xml.XMLConstants; import javax.xml.namespace.NamespaceContext; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * implementation of <code>NamespaceContext</code> */ public class DefaultNamespaceContext implements NamespaceContext { Map<String, String> nsMap = new HashMap<String, String>(); public DefaultNamespaceContext(Map<String, String> nsMap) { this.nsMap = nsMap; } public String getNamespaceURI(String prefix) { if(prefix != null){ return nsMap.get(prefix); } return XMLConstants.NULL_NS_URI; } public String getPrefix(String namespaceURI) { throw new UnsupportedOperationException(); } public Iterator getPrefixes(String namespaceURI) { throw new UnsupportedOperationException(); } }
1,527
26.285714
69
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/PolicyTreeElement.java
/* * @(#)PolicyTreeElement.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana; import org.wso2.balana.ctx.AbstractResult; import org.wso2.balana.ctx.EvaluationCtx; import java.io.OutputStream; import java.net.URI; import java.util.List; /** * This represents a single node in a policy tree. A node is either a policy set, a policy, or a * rule. This interface is used to interact with these node types in a general way. Note that rules * are leaf nodes in a policy tree as they never contain children. * * @since 1.1 * @author seth proctor */ public interface PolicyTreeElement { /** * Returns the <code>List</code> of <code>PolicyTreeElement</code> objects that are the children * of this node. If this node has no children then this list is empty. The children are returned * as a <code>List</code> instead of some unordered collection because in cases like combining * or evaluation the order is often important. * * @return the non-null <code>List</code> of children of this node */ public List getChildren(); /** * Returns the given description of this element or null if there is no description * * @return the description or null */ public String getDescription(); /** * Returns the id of this element * * @return the element's identifier */ public URI getId(); /** * Returns the target for this element or null if there is no target * * @return the element's target */ public AbstractTarget getTarget(); /** * Given the input context sees whether or not the request matches this element's target. The * rules for matching are different depending on the type of element being matched. * * @param context the representation of the request * * @return the result of trying to match this element and the request */ public MatchResult match(EvaluationCtx context); /** * Evaluates this element in the policy tree, and therefore all elements underneath this * element. The rules for evaluation are different depending on the type of element being * evaluated. * * @param context the representation of the request we're evaluating * * @return the result of the evaluation */ public AbstractResult evaluate(EvaluationCtx context); /** * Encodes this <code>PolicyTreeElement</code> into its XML form * * @return <code>String</code> */ public String encode(); /** * Encodes this <code>PolicyTreeElement</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); }
4,585
35.688
104
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/PolicyReference.java
/* * @(#)PolicyReference.java * * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.balana.combine.CombiningAlgorithm; import org.wso2.balana.ctx.AbstractResult; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.ctx.ResultFactory; import org.wso2.balana.ctx.xacml2.Result; import org.wso2.balana.ctx.Status; import org.wso2.balana.finder.PolicyFinder; import org.wso2.balana.finder.PolicyFinderResult; import java.io.OutputStream; import java.io.PrintStream; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; /** * This class is used as a placeholder for the PolicyIdReference and PolicySetIdReference fields in * a PolicySetType. When a reference is used in a policy set, it is telling the PDP to use an * external policy in the current policy. Each time the PDP needs to evaluate that policy reference, * it asks the policy finder for the policy. Typically the policy finder will have cached the * referenced policy, so this isn't too slow. * <p> * NOTE: all of the accessor methods, the match method, and the evaluate method require this class * to ask its <code>PolicyFinder</code> for the referenced policy, which can be a slow operation. * Care should be taken, therefore in calling these methods too often. Also note that it's not safe * to cache the results of these calls, since the referenced policy may change. * * @since 1.0 * @author Seth Proctor */ public class PolicyReference extends AbstractPolicy { /** * Identifies this as a reference to a <code>Policy</code> */ public static final int POLICY_REFERENCE = 0; /** * Identifies this as a reference to a <code>PolicySet</code> */ public static final int POLICYSET_REFERENCE = 1; // the reference private URI reference; // the reference type private int policyType; // and version constraints on this reference private VersionConstraints constraints; // the finder to use in finding the referenced policy private PolicyFinder finder; // the meta-data for the parent policy private PolicyMetaData parentMetaData; // the logger we'll use for all messages private static final Log logger = LogFactory.getLog(PolicyReference.class); /** * Creates a new <code>PolicyReference</code> instance. This has no constraints on version * matching. Note that an XACML 1.x reference may not have any constraints. * * @param reference the reference to the policy * @param policyType one of the two fields in this class * @param finder the <code>PolicyFinder</code> used to handle the reference * @param parentMetaData the meta-data associated with the containing (parent) policy * * @throws IllegalArgumentException if the input policyType isn't valid */ public PolicyReference(URI reference, int policyType, PolicyFinder finder, PolicyMetaData parentMetaData) throws IllegalArgumentException { this(reference, policyType, new VersionConstraints(null, null, null), finder, parentMetaData); } /** * Creates a new <code>PolicyReference</code> instance with version constraints. Note that an * XACML 1.x reference may not have any constraints. * * @param reference the reference to the policy * @param policyType one of the two fields in this class * @param constraints any optional constraints on the version of the referenced policy (this is * never null, but it may impose no constraints, and in fact will never impose * constraints when used from a pre-2.0 XACML policy) * @param finder the <code>PolicyFinder</code> used to handle the reference * @param parentMetaData the meta-data associated with the containing (parent) policy * * @throws IllegalArgumentException if the input policyType isn't valid */ public PolicyReference(URI reference, int policyType, VersionConstraints constraints, PolicyFinder finder, PolicyMetaData parentMetaData) throws IllegalArgumentException { // check if input policyType is a valid value if ((policyType != POLICY_REFERENCE) && (policyType != POLICYSET_REFERENCE)) throw new IllegalArgumentException("Input policyType is not a" + "valid value"); this.reference = reference; this.policyType = policyType; this.constraints = constraints; this.finder = finder; this.parentMetaData = parentMetaData; } /** * Creates an instance of a <code>PolicyReference</code> object based on a DOM node. * * @deprecated As of 2.0 you should avoid using this method and should instead use the version * that takes a <code>PolicyMetaData</code> instance. This method will only work for * XACML 1.x policies. * * @param root the DOM root of a PolicyIdReference or a PolicySetIdReference XML type * @param finder the <code>PolicyFinder</code> used to handle the reference * @return an instance of PolicyReference * @exception ParsingException if the node is invalid */ public static PolicyReference getInstance(Node root, PolicyFinder finder) throws ParsingException { return getInstance(root, finder, new PolicyMetaData()); } /** * Creates an instance of a <code>PolicyReference</code> object based on a DOM node. * * @param root the DOM root of a PolicyIdReference or a PolicySetIdReference XML type * @param finder the <code>PolicyFinder</code> used to handle the reference * @param metaData the meta-data associated with the containing policy * @return an instance of PolicyReference * @exception ParsingException if the node is invalid */ public static PolicyReference getInstance(Node root, PolicyFinder finder, PolicyMetaData metaData) throws ParsingException { URI reference; int policyType; // see what type of reference we are String name = DOMHelper.getLocalName(root); if (name.equals("PolicyIdReference")) { policyType = POLICY_REFERENCE; } else if (name.equals("PolicySetIdReference")) { policyType = POLICYSET_REFERENCE; } else { throw new ParsingException("Unknown reference type: " + name); } // next get the reference try { reference = new URI(root.getFirstChild().getNodeValue()); } catch (Exception e) { throw new ParsingException("Invalid URI in Reference", e); } // now get any constraints NamedNodeMap map = root.getAttributes(); String versionConstraint = null; Node versionNode = map.getNamedItem("Version"); if (versionNode != null) versionConstraint = versionNode.getNodeValue(); String earlyConstraint = null; Node earlyNode = map.getNamedItem("EarliestVersion"); if (earlyNode != null) earlyConstraint = earlyNode.getNodeValue(); String lateConstraint = null; Node lateNode = map.getNamedItem("LatestVersion"); if (lateNode != null) lateConstraint = lateNode.getNodeValue(); VersionConstraints constraints = new VersionConstraints(versionConstraint, earlyConstraint, lateConstraint); // finally, create the reference return new PolicyReference(reference, policyType, constraints, finder, metaData); } /** * Returns the reference identifier used to resolve the policy. * * @return the reference <code>URI</code> */ public URI getReference() { return reference; } /** * Returns the version constraints associated with this reference. This will never be null, * though the constraints may be empty. * * @return the version constraints */ public VersionConstraints getConstraints() { return constraints; } /** * Returns whether this is a reference to a policy or to a policy set. * * @return the reference type, either <code>POLICY_REFERENCE</code> or * <code>POLICYSET_REFERENCE</code> */ public int getReferenceType() { return policyType; } /** * Returns the id of this policy. If the policy is invalid or can't be retrieved, then a runtime * exception is thrown. * * @return the policy id * * @throws ProcessingException if the referenced policy can't be retrieved */ public URI getId() { return resolvePolicy().getId(); } /** * Returns the version of this policy. If the policy is invalid or can't be retrieved, then a * runtime exception is thrown. * * @return the policy version * * @throws ProcessingException if the referenced policy can't be retrieved */ public String getVersion() { return resolvePolicy().getVersion(); } /** * Returns the combining algorithm used by this policy. If the policy is invalid or can't be * retrieved, then a runtime exception is thrown. * * @return the combining algorithm * * @throws ProcessingException if the referenced policy can't be retrieved */ public CombiningAlgorithm getCombiningAlg() { return resolvePolicy().getCombiningAlg(); } /** * Returns the given description of this policy or null if there is no description. If the * policy is invalid or can't be retrieved, then a runtime exception is thrown. * * @return the description or null * * @throws ProcessingException if the referenced policy can't be retrieved */ public String getDescription() { return resolvePolicy().getDescription(); } /** * Returns the target for this policy. If the policy is invalid or can't be retrieved, then a * runtime exception is thrown. * * @return the policy's target * * @throws ProcessingException if the referenced policy can't be retrieved */ public AbstractTarget getTarget() { return resolvePolicy().getTarget(); } /** * Returns the default version for this policy. If the policy is invalid or can't be retrieved, * then a runtime exception is thrown. * * @return the policy's default version * * @throws ProcessingException if the referenced policy can't be retrieved */ public String getDefaultVersion() { return resolvePolicy().getDefaultVersion(); } /** * Returns the child policy nodes under this node in the policy tree. If the policy is invalid * or can't be retrieved, then a runtime exception is thrown. * * @return the <code>List</code> of child policy nodes * * @throws ProcessingException if the referenced policy can't be retrieved */ public List getChildren() { return resolvePolicy().getChildren(); } /** * Returns the child policy nodes and their associated parameters. If the policy is invalid or * can't be retrieved, then a runtime exception is thrown. * * @return a <code>List</code> of <code>CombinerElement</code>s * * @throws ProcessingException if the referenced policy can't be retrieved */ public List getChildElements() { return resolvePolicy().getChildElements(); } /** * Returns the Set of obligations for this policy, which may be empty if there are no * obligations. If the policy is invalid or can't be retrieved, then a runtime exception is * thrown. * * @return the policy's obligations * * @throws ProcessingException if the referenced policy can't be retrieved */ public Set getObligationExpressions() { return resolvePolicy().getObligationExpressions(); } /** * Returns the meta-data associated with this policy. If the policy is invalid or can't be * retrieved, then a runtime exception is thrown. Note that this is the meta-data for the * referenced policy, not the meta-data for the parent policy (which is what gets provided to * the constructors of this class). * * @return the policy's meta-data * * @throws ProcessingException if the referenced policy can't be retrieved */ public PolicyMetaData getMetaData() { return resolvePolicy().getMetaData(); } /** * 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); } } /** * Private helper method that tried to resolve the policy */ private AbstractPolicy resolvePolicy() { // see if this reference was setup with a finder if (finder == null) { if (logger.isWarnEnabled()) { logger.warn("PolicyReference with id " + reference.toString() + " was queried but was " + "not configured with a PolicyFinder"); } throw new ProcessingException("couldn't find the policy with " + "a null finder"); } PolicyFinderResult pfr = finder.findPolicy(reference, policyType, constraints, parentMetaData); if (pfr.notApplicable()) throw new ProcessingException("couldn't resolve the policy"); if (pfr.indeterminate()) throw new ProcessingException("error resolving the policy"); return pfr.getPolicy(); } /** * 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); } /** * Encodes this <code>PolicyReference</code> into its XML form * * @return <code>String</code> */ public String encode() { StringBuilder builder = new StringBuilder(); encode(builder); return builder.toString(); } /** * Encodes this <code>PolicyReference</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) { if (policyType == POLICY_REFERENCE) { builder.append("<PolicyIdReference").append(encodeConstraints()).append(">"). append(reference.toString()).append("</PolicyIdReference>"); } else { builder.append("<PolicySetIdReference").append(encodeConstraints()).append(">"). append(reference.toString()).append("</PolicySetIdReference>"); } } /** * Private helper method that encodes the variable constraints info. Note that if this is a * pre-2.0 policy the constraints are always null, so nothing will be added here. * @return */ private String encodeConstraints() { String str = ""; VersionConstraints version = getConstraints(); String v = version.getVersionConstraint(); if (v != null) str += " Version=\"" + v + "\""; String e = version.getEarliestConstraint(); if (e != null) str += " EarliestVersion=\"" + e + "\""; String l = version.getLatestConstraint(); if (l != null) str += " LatestVersion=\"" + l + "\""; return str; } }
19,746
37.418288
113
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/PolicyMetaData.java
/* * @(#)PolicyMetaData.java * * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana; import org.wso2.balana.attr.AttributeFactoryProxy; import org.wso2.balana.combine.CombiningAlgFactoryProxy; import org.wso2.balana.cond.FunctionFactoryProxy; /** * This is used to share polcy meta-data throughout the policy tree. Examples of common meta-data * include the version of XACML or XPath being used in a policy. * * @since 2.0 * @author Seth Proctor */ public class PolicyMetaData { /** * The default version of XACML, 1.0, used if no namespace string is specified */ public static final int XACML_DEFAULT_VERSION = XACMLConstants.XACML_VERSION_1_0; // private mapping from XACML version number to identifier string private static String[] xacmlIdentifiers = { XACMLConstants.XACML_1_0_IDENTIFIER, XACMLConstants.XACML_1_0_IDENTIFIER, XACMLConstants.XACML_2_0_IDENTIFIER, XACMLConstants.XACML_3_0_IDENTIFIER }; /** * XPath 1.0 identifier */ public static final String XPATH_1_0_IDENTIFIER = "http://www.w3.org/TR/1999/Rec-xpath-19991116"; /** * Version identifier for an unspecified version of XPath */ public static final int XPATH_VERSION_UNSPECIFIED = 0; /** * Version identifier for XPath 1.0 */ public static final int XPATH_VERSION_1_0 = 1; // private mapping from XPath version number to identifier string private static String[] xpathIdentifiers = { null, XPATH_1_0_IDENTIFIER }; // the version of XACML private int xacmlVersion; // the version of XPath, or null if none is specified private int xpathVersion; /** * Creates a <code>PolicyMetaData</code> instance with all the parameters set to their default * values. */ public PolicyMetaData() { this(XACML_DEFAULT_VERSION, XPATH_VERSION_UNSPECIFIED); } /** * Creates a <code>PolicyMetaData</code> instance with the given parameters. A proxy value of * null implies the default factory. * * @param xacmlVersion the version of XACML used in a policy * @param xpathVersion the XPath version to use in any selectors */ public PolicyMetaData(int xacmlVersion, int xpathVersion) { this.xacmlVersion = xacmlVersion; this.xpathVersion = xpathVersion; } /** * Creates a <code>PolicyMetaData</code> instance with the given parameters. * * @param xacmlVersion the version of XACML used in a policy * @param xpathVersion the XPath version to use in any selectors, or null if this is unspecified * (ie, not supplied in the defaults section of the policy) * the XACML policy, if null use default factories * @throws IllegalArgumentException if the identifier strings are unknown */ public PolicyMetaData(String xacmlVersion, String xpathVersion) { if (xacmlVersion == null){ this.xacmlVersion = XACML_DEFAULT_VERSION; } else if (xacmlVersion.equals(XACMLConstants.XACML_1_0_IDENTIFIER)){ this.xacmlVersion = XACMLConstants.XACML_VERSION_1_0; } else if (xacmlVersion.equals(XACMLConstants.XACML_2_0_IDENTIFIER)){ this.xacmlVersion = XACMLConstants.XACML_VERSION_2_0; } else if (xacmlVersion.equals(XACMLConstants.XACML_3_0_IDENTIFIER)){ this.xacmlVersion = XACMLConstants.XACML_VERSION_3_0; } else { throw new IllegalArgumentException("Unknown XACML version " + "string: " + xacmlVersion); } if (xpathVersion != null) { // if (!xpathVersion.equals(XPATH_1_0_IDENTIFIER)){ // throw new IllegalArgumentException("Unsupported XPath " + " version: " // + xpathVersion); // } this.xpathVersion = XPATH_VERSION_1_0; } else { this.xpathVersion = XPATH_VERSION_UNSPECIFIED; } } /** * Returns which version of XACML is specified in this meta-data. * * @return the XACML version */ public int getXACMLVersion() { return xacmlVersion; } /** * Returns the identifier string for the specified version of XACML. * * @return the identifier string */ public String getXACMLIdentifier() { return xacmlIdentifiers[xacmlVersion]; } /** * Returns which version of XPath is specified in this meta-data. * * @return the XPath version or null */ public int getXPathVersion() { return xpathVersion; } /** * Returns the identifier string for the specified version of XPath, or null if no version is * specified. * * @return the identifier string or null */ public String getXPathIdentifier() { return xpathIdentifiers[xpathVersion]; } }
6,617
36.179775
101
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/Balana.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.balana.attr.AttributeFactory; import org.wso2.balana.combine.CombiningAlgFactory; import org.wso2.balana.cond.FunctionFactory; import org.wso2.balana.finder.AttributeFinder; import org.wso2.balana.finder.AttributeFinderModule; import org.wso2.balana.finder.PolicyFinder; import org.wso2.balana.finder.PolicyFinderModule; import org.wso2.balana.finder.impl.CurrentEnvModule; import org.wso2.balana.finder.impl.FileBasedPolicyFinderModule; import org.wso2.balana.finder.impl.SelectorModule; import org.wso2.balana.utils.Utils; import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * This is the core class for the Balana project providing the init point of Balana engine. * */ public class Balana { /** * PDP configuration of Balana engine instance */ private PDPConfig pdpConfig; /** * Attribute factory that supports in Balana engine instance */ private AttributeFactory attributeFactory; /** * Target Function factory that supports in Balana engine instance */ private FunctionFactory functionTargetFactory; /** * Condition Function factory that supports in Balana engine instance */ private FunctionFactory functionConditionFactory; /** * General function factory that supports in Balana engine instance */ private FunctionFactory functionGeneralFactory; /** * combining factory that supports in Balana engine instance */ private CombiningAlgFactory combiningAlgFactory; /** * builders to build XACML request */ private DocumentBuilderFactory builder; /** * lock */ private final static Object lock = new Object(); /** * One instance of Balana engine is created. */ private static Balana balana; /** * Logger instance */ private static final Log logger = LogFactory.getLog(Balana.class); /** * This constructor creates the Balana engine instance. First, it loads all configuration * from store and creates Balan engine with given configuration names. * If no configuration name is given, loads default configurations of the configuration store. * If configuration store does not configured or any error in building, It create default Balana * engine. * * @param pdpConfigName pdp configuration name * @param attributeFactoryName attribute factory name * @param functionFactoryName function factory name * @param combiningAlgFactoryName combine factory name */ private Balana(String pdpConfigName, String attributeFactoryName, String functionFactoryName, String combiningAlgFactoryName) { ConfigurationStore store = null; try { if(System.getProperty(ConfigurationStore.PDP_CONFIG_PROPERTY) != null){ store = new ConfigurationStore(); } else { String configFile = (new File(".")).getCanonicalPath() + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + "config.xml"; File file = new File(configFile); if(file.exists()) { store = new ConfigurationStore(new File(configFile)); } } if(store != null){ if(pdpConfigName != null){ pdpConfig = store.getPDPConfig(pdpConfigName); } else { pdpConfig = store.getDefaultPDPConfig(); } if(attributeFactoryName != null){ this.attributeFactory = store.getAttributeFactory(attributeFactoryName); } else { this.attributeFactory = store.getDefaultAttributeFactoryProxy().getFactory(); } if(functionFactoryName != null){ this.functionTargetFactory = store. getFunctionFactoryProxy(functionFactoryName).getTargetFactory(); } else { this.functionTargetFactory = store. getDefaultFunctionFactoryProxy().getTargetFactory(); } if(functionFactoryName != null){ this.functionConditionFactory = store. getFunctionFactoryProxy(functionFactoryName).getConditionFactory(); } else { this.functionConditionFactory = store. getDefaultFunctionFactoryProxy().getConditionFactory(); } if(functionFactoryName != null){ this.functionGeneralFactory = store. getFunctionFactoryProxy(functionFactoryName).getGeneralFactory(); } else { this.functionGeneralFactory = store. getDefaultFunctionFactoryProxy().getGeneralFactory(); } if(functionFactoryName != null){ this.combiningAlgFactory = store.getCombiningAlgFactory(functionFactoryName); } else { this.combiningAlgFactory = store.getDefaultCombiningFactoryProxy().getFactory(); } } } catch (Exception e) { // just ignore all exceptions as all are init again with default configurations } if(pdpConfig == null){ //creating default one with Balana engine. PolicyFinder policyFinder = new PolicyFinder(); Set<PolicyFinderModule> policyFinderModules = new HashSet<PolicyFinderModule>(); FileBasedPolicyFinderModule fileBasedPolicyFinderModule = new FileBasedPolicyFinderModule(); policyFinderModules.add(fileBasedPolicyFinderModule); policyFinder.setModules(policyFinderModules); AttributeFinder attributeFinder = new AttributeFinder(); List<AttributeFinderModule> attributeFinderModules = new ArrayList<AttributeFinderModule>(); SelectorModule selectorModule = new SelectorModule(); CurrentEnvModule currentEnvModule = new CurrentEnvModule(); attributeFinderModules.add(selectorModule); attributeFinderModules.add(currentEnvModule); attributeFinder.setModules(attributeFinderModules); pdpConfig = new PDPConfig(attributeFinder, policyFinder, null, false); } if(attributeFactory == null){ attributeFactory = AttributeFactory.getInstance(); } if(functionTargetFactory == null){ functionTargetFactory = FunctionFactory.getInstance().getTargetFactory(); } if(functionConditionFactory == null){ functionConditionFactory = FunctionFactory.getInstance().getConditionFactory(); } if(functionGeneralFactory == null){ functionGeneralFactory = FunctionFactory.getInstance().getGeneralFactory(); } if(combiningAlgFactory == null){ combiningAlgFactory = CombiningAlgFactory.getInstance(); } // init builder this.builder = Utils.getSecuredDocumentBuilderFactory(); } /** * Get instance of Balana engine * * @return returns <code>Balana</code> */ public static Balana getInstance(){ if(balana == null){ synchronized (lock){ if(balana == null){ balana = new Balana(null, null, null, null); } } } return balana; } /** * Get instance of Balana engine for given common identifier * * @param identifier identifier name * @return returns <code>Balana</code> */ public Balana getInstance(String identifier){ if(balana == null){ synchronized (lock){ if(balana == null){ balana = new Balana(identifier, identifier, identifier, identifier); } } } return balana; } /** * Get instance of Balana engine for given identifiers * * @param pdpConfigName pdp configuration name * @param attributeFactoryName attribute factory name * @param functionFactoryName function factory name * @param combiningAlgFactoryName combine factory name * @return returns <code>Balana</code> */ public Balana getInstance(String pdpConfigName, String attributeFactoryName, String functionFactoryName, String combiningAlgFactoryName){ if(balana == null){ synchronized (lock){ if(balana == null){ balana = new Balana(pdpConfigName, attributeFactoryName, functionFactoryName, combiningAlgFactoryName); } } } return balana; } public PDPConfig getPdpConfig() { return pdpConfig; } public void setPdpConfig(PDPConfig pdpConfig) { this.pdpConfig = pdpConfig; } public AttributeFactory getAttributeFactory() { return attributeFactory; } public void setAttributeFactory(AttributeFactory attributeFactory) { this.attributeFactory = attributeFactory; } public FunctionFactory getFunctionTargetFactory() { return functionTargetFactory; } public void setFunctionTargetFactory(FunctionFactory functionTargetFactory) { this.functionTargetFactory = functionTargetFactory; } public FunctionFactory getFunctionConditionFactory() { return functionConditionFactory; } public void setFunctionConditionFactory(FunctionFactory functionConditionFactory) { this.functionConditionFactory = functionConditionFactory; } public FunctionFactory getFunctionGeneralFactory() { return functionGeneralFactory; } public void setFunctionGeneralFactory(FunctionFactory functionGeneralFactory) { this.functionGeneralFactory = functionGeneralFactory; } public CombiningAlgFactory getCombiningAlgFactory() { return combiningAlgFactory; } public void setCombiningAlgFactory(CombiningAlgFactory combiningAlgFactory) { this.combiningAlgFactory = combiningAlgFactory; } public DocumentBuilderFactory getBuilder() { return builder; } }
11,526
33.930303
108
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/TargetMatch.java
/* * @(#)TargetMatch.java * * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana; import org.wso2.balana.attr.*; import org.wso2.balana.cond.Evaluatable; import org.wso2.balana.cond.EvaluationResult; import org.wso2.balana.cond.Function; import org.wso2.balana.cond.FunctionFactory; import org.wso2.balana.cond.FunctionTypeException; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.ctx.Status; import java.io.OutputStream; import java.io.PrintStream; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Represents the SubjectMatch, ResourceMatch, ActionMatch, or EnvironmentMatch (in XACML 2.0 and * later) XML types in XACML, depending on the value of the type field. This is the part of the * Target that actually evaluates whether the specified attribute values in the Target match the * corresponding attribute values in the request context. * * @since 1.0 * @author Seth Proctor */ public class TargetMatch { /** * An integer value indicating that this class represents a SubjectMatch */ public static final int SUBJECT = 0; /** * An integer value indicating that this class represents a ResourceMatch */ public static final int RESOURCE = 1; /** * An integer value indicating that this class represents an ActionMatch */ public static final int ACTION = 2; /** * An integer value indicating that this class represents an EnvironmentMatch */ public static final int ENVIRONMENT = 3; /** * Mapping from the 4 match types to their string representations */ public static final String[] NAMES = { "Subject", "Resource", "Action", "Environment"}; // the type of this target match // if there is no type, value is zero private int type; // the function used for matching private Function function; // the designator or selector private Evaluatable eval; // the value private AttributeValue attrValue; /** * Constructor that creates a <code>TargetMatch</code> from components. * * @param type an integer indicating whether this class represents a SubjectMatch, * ResourceMatch, or ActionMatch * @param function the <code>Function</code> that represents the MatchId * @param eval the <code>AttributeDesignator</code> or <code>AttributeSelector</code> to be used * to select attributes from the request context * @param attrValue the <code>AttributeValue</code> to compare against * * @throws IllegalArgumentException if the input type isn't a valid value */ public TargetMatch(int type, Function function, Evaluatable eval, AttributeValue attrValue) throws IllegalArgumentException { // check if input type is a valid value if ((type != SUBJECT) && (type != RESOURCE) && (type != ACTION) && (type != ENVIRONMENT)) throw new IllegalArgumentException("Unknown TargetMatch type"); this.type = type; this.function = function; this.eval = eval; this.attrValue = attrValue; } /** * Constructor that creates a <code>TargetMatch</code> from components. * * @param function the <code>Function</code> that represents the MatchId * @param eval the <code>AttributeDesignator</code> or <code>AttributeSelector</code> to be used * to select attributes from the request context * @param attrValue the <code>AttributeValue</code> to compare against * * @throws IllegalArgumentException if the input type isn't a valid value */ public TargetMatch(Function function, Evaluatable eval, AttributeValue attrValue) throws IllegalArgumentException { this.function = function; this.eval = eval; this.attrValue = attrValue; } /** * Creates a <code>TargetMatch</code> by parsing a node, using the input prefix to determine * whether this is a SubjectMatch, ResourceMatch, or ActionMatch. * * @deprecated As of 2.0 you should avoid using this method and should instead use the version * that takes a <code>PolicyMetaData</code> instance. This method will only work for * XACML 1.x policies. * * @param root the node to parse for the <code>TargetMatch</code> * @param prefix a String indicating what type of <code>TargetMatch</code> to instantiate * (Subject, Resource, or Action) * @param xpathVersion the XPath version to use in any selectors, or null if this is unspecified * (ie, not supplied in the defaults section of the policy) * * @return a new <code>TargetMatch</code> constructed by parsing * * @throws org.wso2.balana.ParsingException if there was an error during parsing * @throws IllegalArgumentException if the input prefix isn't a valid value */ public static TargetMatch getInstance(Node root, String prefix, String xpathVersion) throws ParsingException, IllegalArgumentException { int i = 0; while ((i < NAMES.length) && (!NAMES[i].equals(prefix))) i++; if (i == NAMES.length) throw new IllegalArgumentException("Unknown TargetMatch type"); return getInstance(root, i, new PolicyMetaData(XACMLConstants.XACML_1_0_IDENTIFIER, xpathVersion)); } public static TargetMatch getInstance(Node root, PolicyMetaData metaData) throws ParsingException { return getInstance(root, 0, metaData); } /** * Creates a <code>TargetMatch</code> by parsing a node, using the input prefix to determine * whether this is a SubjectMatch, ResourceMatch, or ActionMatch. * * @param root the node to parse for the <code>TargetMatch</code> * @param matchType the type of <code>TargetMatch</code> as specified by the SUBJECT, RESOURCE, * ACTION, or ENVIRONMENT fields * @param metaData the policy's meta-data * * @return a new <code>TargetMatch</code> constructed by parsing * * @throws ParsingException if there was an error during parsing */ public static TargetMatch getInstance(Node root, int matchType, PolicyMetaData metaData) throws ParsingException { Function function; Evaluatable eval = null; AttributeValue attrValue = null; AttributeFactory attrFactory = Balana.getInstance().getAttributeFactory(); // get the function type, making sure that it's really a correct // Target function String funcName = root.getAttributes().getNamedItem("MatchId").getNodeValue(); FunctionFactory factory = FunctionFactory.getTargetInstance(); try { URI funcId = new URI(funcName); function = factory.createFunction(funcId); } catch (URISyntaxException use) { throw new ParsingException("Error parsing TargetMatch", use); } catch (UnknownIdentifierException uie) { throw new ParsingException("Unknown MatchId", uie); } catch (FunctionTypeException fte) { // try to create an abstract function try { URI funcId = new URI(funcName); function = factory.createAbstractFunction(funcId, root); } catch (Exception e) { // any exception here is an error throw new ParsingException("invalid abstract function", e); } } // next, get the designator or selector being used, and the attribute // value paired with it NodeList nodes = root.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); String name = DOMHelper.getLocalName(node); if (XACMLConstants.XACML_VERSION_3_0 == metaData.getXACMLVersion() && "AttributeDesignator".equals(name)){ eval = AttributeDesignatorFactory.getFactory().getAbstractDesignator(node, metaData); } else if(!(XACMLConstants.XACML_VERSION_3_0 == metaData.getXACMLVersion()) && (NAMES[matchType] + "AttributeDesignator").equals(name)){ eval = AttributeDesignatorFactory.getFactory().getAbstractDesignator(node, metaData); } else if (name.equals("AttributeSelector")) { eval = AttributeSelectorFactory.getFactory().getAbstractSelector(node, metaData); } else if (name.equals("AttributeValue")) { try { attrValue = attrFactory.createValue(node); } catch (UnknownIdentifierException uie) { throw new ParsingException("Unknown Attribute Type", uie); } } } // finally, check that the inputs are valid for this function List<Evaluatable> inputs = new ArrayList<Evaluatable>(); inputs.add(attrValue); inputs.add(eval); function.checkInputsNoBag(inputs); if(XACMLConstants.XACML_VERSION_3_0 == metaData.getXACMLVersion()){ return new TargetMatch(function, eval, attrValue); } else { return new TargetMatch(matchType, function, eval, attrValue); } } /** * Returns the type of this <code>TargetMatch</code>, either <code>SUBJECT</code>, * <code>RESOURCE</code>, <code>ACTION</code>, or <code>ENVIRONMENT</code>. * * @return the type */ public int getType() { return type; } /** * Returns the <code>Function</code> used to do the matching. * * @return the match function */ public Function getMatchFunction() { return function; } /** * Returns the <code>AttributeValue</code> used by the matching function. * * @return the <code>AttributeValue</code> for the match */ public AttributeValue getMatchValue() { return attrValue; } /** * Returns the <code>AttributeDesignator</code> or <code>AttributeSelector</code> used by the * matching function. * * @return the designator or selector for the match */ public Evaluatable getMatchEvaluatable() { return eval; } /** * Determines whether this <code>TargetMatch</code> matches the input request (whether it is * applicable) * * @param context the representation of the request * * @return the result of trying to match the TargetMatch and the request */ public MatchResult match(EvaluationCtx context) { // start by evaluating the AD/AS EvaluationResult result = eval.evaluate(context); if (result.indeterminate()) { // in this case, we don't ask the function for anything, and we // simply return INDETERMINATE return new MatchResult(MatchResult.INDETERMINATE, result.getStatus()); } // an AD/AS will always return a bag BagAttribute bag = (BagAttribute) (result.getAttributeValue()); if (!bag.isEmpty()) { // we got back a set of attributes, so we need to iterate through // them, seeing if at least one matches Iterator it = bag.iterator(); boolean atLeastOneError = false; Status firstIndeterminateStatus = null; while (it.hasNext()) { ArrayList<Evaluatable> inputs = new ArrayList<Evaluatable>(); inputs.add(attrValue); inputs.add((Evaluatable)it.next()); // do the evaluation MatchResult match = evaluateMatch(inputs, context); // we only need one match for this whole thing to match if (match.getResult() == MatchResult.MATCH) { if (attrValue instanceof StringAttribute) { match.setPolicyValue(((StringAttribute) attrValue).getValue()); } return match; } // if it was INDETERMINATE, we want to remember for later if (match.getResult() == MatchResult.INDETERMINATE) { atLeastOneError = true; // there are no rules about exactly what status data // should be returned here, so like in the combining // algs, we'll just track the first error if (firstIndeterminateStatus == null) firstIndeterminateStatus = match.getStatus(); } } // if we got here, then nothing matched, so we'll either return // INDETERMINATE or NO_MATCH if (atLeastOneError) return new MatchResult(MatchResult.INDETERMINATE, firstIndeterminateStatus); else return new MatchResult(MatchResult.NO_MATCH); } else { // this is just an optimization, since the loop above will // actually handle this case, but this is just a little // quicker way to handle an empty bag return new MatchResult(MatchResult.NO_MATCH); } } /** * 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); } /** * Encodes this <code>TargetMatch</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) { String tagName = "Match"; if(type != 0){ tagName = NAMES[type] + "Match"; } builder.append("<").append(tagName).append(" MatchId=\""). append(function.getIdentifier().toString()).append("\">\n"); attrValue.encode(builder); eval.encode(builder); builder.append("</").append(tagName).append(">\n"); } }
16,775
37.654378
111
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/PDPConfig.java
/* * @(#)PDPConfig.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana; import org.wso2.balana.finder.AttributeFinder; import org.wso2.balana.finder.PolicyFinder; import org.wso2.balana.finder.ResourceFinder; /** * This class is used as a container that holds configuration information for the PDP, which * includes the <code>AttributeFinder</code>, <code>PolicyFinder</code>, and * <code>ResourceFinder</code> that the PDP should use. * * @since 1.0 * @author Seth Proctor * @author Marco Barreno */ public class PDPConfig { // private AttributeFinder attributeFinder; // private PolicyFinder policyFinder; // private ResourceFinder resourceFinder; // private boolean multipleRequestHandle; /** * Constructor that creates a <code>PDPConfig</code> from components. * * @param attributeFinder the <code>AttributeFinder</code> that the PDP should use, or null if * it shouldn't use any * @param policyFinder the <code>PolicyFinder</code> that the PDP should use, or null if it * shouldn't use any * @param resourceFinder the <code>ResourceFinder</code> that the PDP should use, or null if it * shouldn't use any */ public PDPConfig(AttributeFinder attributeFinder, PolicyFinder policyFinder, ResourceFinder resourceFinder) { this(attributeFinder, policyFinder, resourceFinder, true); } /** * Constructor that creates a <code>PDPConfig</code> from components. * * @param attributeFinder the <code>AttributeFinder</code> that the PDP should use, or null if * it shouldn't use any * @param policyFinder the <code>PolicyFinder</code> that the PDP should use, or null if it * shouldn't use any * @param resourceFinder the <code>ResourceFinder</code> that the PDP should use, or null if it * shouldn't use any * @param multipleRequestHandle whether PDP capable of handling multiple requests or not */ public PDPConfig(AttributeFinder attributeFinder, PolicyFinder policyFinder, ResourceFinder resourceFinder, boolean multipleRequestHandle) { if (attributeFinder != null) this.attributeFinder = attributeFinder; else this.attributeFinder = new AttributeFinder(); if (policyFinder != null) this.policyFinder = policyFinder; else this.policyFinder = new PolicyFinder(); if (resourceFinder != null) this.resourceFinder = resourceFinder; else this.resourceFinder = new ResourceFinder(); this.multipleRequestHandle = multipleRequestHandle; } /** * Returns the <code>AttributeFinder</code> that was configured, or null if none was configured * * @return the <code>AttributeFinder</code> or null */ public AttributeFinder getAttributeFinder() { return attributeFinder; } /** * Returns the <code>PolicyFinder</code> that was configured, or null if none was configured * * @return the <code>PolicyFinder</code> or null */ public PolicyFinder getPolicyFinder() { return policyFinder; } /** * Returns the <code>ResourceFinder</code> that was configured, or null if none was configured * * @return the <code>ResourceFinder</code> or null */ public ResourceFinder getResourceFinder() { return resourceFinder; } /** * Returns the boolean that whether PDP capable of handling multiple requests or not * * @return true or false */ public boolean isMultipleRequestHandle() { return multipleRequestHandle; } }
5,522
36.571429
99
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/ObligationFactory.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana; import org.w3c.dom.Node; import org.wso2.balana.xacml3.ObligationExpression; import java.util.HashMap; /** * */ public class ObligationFactory { private HashMap<String, AbstractObligation> targetMap = new HashMap<String, AbstractObligation>(); private static volatile ObligationFactory factoryInstance; public AbstractObligation getObligation(Node node, PolicyMetaData metaData) throws ParsingException { if(XACMLConstants.XACML_VERSION_3_0 == metaData.getXACMLVersion()){ return ObligationExpression.getInstance(node, metaData); } else { return org.wso2.balana.xacml2.Obligation.getInstance(node); } } /** * Returns an instance of this factory. This method enforces a singleton model, meaning that * this always returns the same instance, creating the factory if it hasn't been requested * before. * * @return the factory instance */ public static ObligationFactory getFactory() { if (factoryInstance == null) { synchronized (ObligationFactory.class) { if (factoryInstance == null) { factoryInstance = new ObligationFactory(); } } } return factoryInstance; } }
1,979
29.461538
105
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/ObligationResult.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana; import org.wso2.balana.ctx.EvaluationCtx;import java.io.OutputStream; /** * */ public interface ObligationResult { /** * Encodes this <code>ObligationResult</code> into its XML form * * @return <code>String</code> */ public String encode(); /** * Encodes this <code>ObligationResult</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); }
1,249
26.777778
103
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/AbstractObligation.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana; import org.wso2.balana.ctx.EvaluationCtx; import java.net.URI; /** * Represents ObligationType in the XACML 2.0 and ObligationExpressionType in the XACML 2.0 * policy schema. AbstractObligation class has been written to provide a unique interface for * both XACML 2.0 and XACML 3.0 * */ public abstract class AbstractObligation { /** * Identifier that uniquely identify the Obligation or ObligationExpression element */ protected URI obligationId; /** * effect that will cause this obligation to be included in a response */ protected int fulfillOn; /** * Evaluates obligation and creates the results * * @param ctx <code>EvaluationCtx</code> * @return <code>ObligationResult</code> */ public abstract ObligationResult evaluate(EvaluationCtx ctx); /** * Returns effect that will cause this obligation to be included in a response * * @return the fulfillOn effect */ public int getFulfillOn(){ return fulfillOn; } /** * Returns the id of this obligation * * @return the id */ public URI getId() { return obligationId; } /** * Encodes this <code>ObligationResult</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 abstract void encode(StringBuilder builder); }
2,168
26.807692
103
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/Policy.java
/* * @(#)Policy.java * * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana; import org.wso2.balana.combine.CombinerElement; import org.wso2.balana.combine.CombinerParameter; import org.wso2.balana.combine.RuleCombinerElement; import org.wso2.balana.combine.RuleCombiningAlgorithm; import org.wso2.balana.cond.VariableDefinition; import org.wso2.balana.cond.VariableManager; import java.net.URI; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Represents one of the two top-level constructs in XACML, the PolicyType. This optionally contains * rules, which in turn contain most of the logic of a policy. * * @since 1.0 * @author Seth Proctor */ public class Policy extends AbstractPolicy { // the set of variable definitions in this policy private Set<VariableDefinition> definitions; /** * Creates a new <code>Policy</code> with only the required elements. * * @param id the policy identifier * @param combiningAlg the <code>CombiningAlgorithm</code> used on the rules in this set * @param target the <code>AbstractTarget</code> for this policy */ public Policy(URI id, RuleCombiningAlgorithm combiningAlg, AbstractTarget target) { this(id, null, combiningAlg, null, target, null, null, null); } /** * Creates a new <code>Policy</code> with only the required elements plus rules. * * @param id the policy identifier * @param combiningAlg the <code>CombiningAlgorithm</code> used on the rules in this set * @param target the <code>AbstractTarget</code> for this policy * @param rules a list of <code>Rule</code> objects * * @throws IllegalArgumentException if the <code>List</code> of rules contains an object that is * not a <code>Rule</code> */ public Policy(URI id, RuleCombiningAlgorithm combiningAlg, AbstractTarget target, List<Rule> rules) { this(id, null, combiningAlg, null, target, null, rules, null); } /** * Creates a new <code>Policy</code> with the required elements plus a version, rules, and a * String description. Note that the version is an XACML 2.0 feature. * * @param id the policy identifier * @param version the policy version or null for the default (this must always be null for XACML * 1.x policies) * @param combiningAlg the <code>CombiningAlgorithm</code> used on the rules in this set * @param description a <code>String</code> describing the policy * @param target the <code>AbstractTarget</code> for this policy * @param rules a list of <code>Rule</code> objects * * @throws IllegalArgumentException if the <code>List</code> of rules contains an object that is * not a <code>Rule</code> */ public Policy(URI id, String version, RuleCombiningAlgorithm combiningAlg, String description, AbstractTarget target, List<Rule> rules) { this(id, version, combiningAlg, description, target, null, rules, null); } /** * Creates a new <code>Policy</code> with the required elements plus a version, rules, a String * description and policy defaults. Note that the version is an XACML 2.0 feature. * * @param id the policy identifier * @param version the policy version or null for the default (this must always be null for XACML * 1.x policies) * @param combiningAlg the <code>CombiningAlgorithm</code> used on the rules in this set * @param description a <code>String</code> describing the policy * @param target the <code>AbstractTarget</code> for this policy * @param defaultVersion the XPath version to use * @param rules a list of <code>Rule</code> objects * * @throws IllegalArgumentException if the <code>List</code> of rules contains an object that is * not a <code>Rule</code> */ public Policy(URI id, String version, RuleCombiningAlgorithm combiningAlg, String description, AbstractTarget target, String defaultVersion, List<Rule> rules) { this(id, version, combiningAlg, description, target, defaultVersion, rules, null); } /** * Creates a new <code>Policy</code> with the required elements plus a version, rules, a String * description, policy defaults, and obligations. Note that the version is an XACML 2.0 feature. * * @param id the policy identifier * @param version the policy version or null for the default (this must always be null for XACML * 1.x policies) * @param combiningAlg the <code>CombiningAlgorithm</code> used on the rules in this set * @param description a <code>String</code> describing the policy * @param target the <code>AbstractTarget</code> for this policy * @param defaultVersion the XPath version to use * @param rules a list of <code>Rule</code> objects * @param obligations a set of <code>Obligations</code> objects * * @throws IllegalArgumentException if the <code>List</code> of rules contains an object that is * not a <code>Rule</code> */ public Policy(URI id, String version, RuleCombiningAlgorithm combiningAlg, String description, AbstractTarget target, String defaultVersion, List<Rule> rules, Set<AbstractObligation> obligations) { this(id, version, combiningAlg, description, target, defaultVersion, rules, obligations, null); } /** * Creates a new <code>Policy</code> with the required elements plus a version, rules, a String * description, policy defaults, obligations, and variable definitions. Note that the version * and definitions are XACML 2.0 features. * * @param id the policy identifier * @param version the policy version or null for the default (this must always be null for XACML * 1.x policies) * @param combiningAlg the <code>CombiningAlgorithm</code> used on the rules in this set * @param description a <code>String</code> describing the policy * @param target the <code>AbstractTarget</code> for this policy * @param defaultVersion the XPath version to use * @param rules a list of <code>Rule</code> objects * @param obligations a set of <code>Obligations</code> objects * @param definitions a set of <code>VariableDefinition</code> objects that must provide all * definitions referenced by all <code>VariableReference</code>s in the policy * * @throws IllegalArgumentException if the <code>List</code> of rules contains an object that is * not a <code>Rule</code> */ public Policy(URI id, String version, RuleCombiningAlgorithm combiningAlg, String description, AbstractTarget target, String defaultVersion, List<Rule> rules, Set<AbstractObligation> obligations, Set<VariableDefinition> definitions) { super(id, version, combiningAlg, description, target, defaultVersion, obligations, null, null); List<CombinerElement> list = null; // check that the list contains only rules if (rules != null) { list = new ArrayList<CombinerElement>(); for (Rule rule : rules) { list.add(new RuleCombinerElement(rule)); } } setChildren(list); // save the definitions if (definitions == null) this.definitions = new HashSet<VariableDefinition>(); else this.definitions = Collections.unmodifiableSet(new HashSet<VariableDefinition>(definitions)); } /** * Creates a new <code>Policy</code> with the required and optional elements. If you need to * provide combining algorithm parameters, you need to use this constructor. Note that unlike * the other constructors in this class, the rules list is actually a list of * <code>CombinerElement</code>s used to match a rule with any combiner parameters it may have. * * @param id the policy identifier * @param version the policy version or null for the default (this must always be null for XACML * 1.x policies) * @param combiningAlg the <code>CombiningAlgorithm</code> used on the rules in this set * @param description a <code>String</code> describing the policy or null if there is no * description * @param target the <code>AbstractTarget</code> for this policy * @param defaultVersion the XPath version to use or null if there is no default version * @param ruleElements a list of <code>RuleCombinerElement</code> objects or null if there are * no rules * @param obligations a set of <code>Obligations</code> objects or null if there are no * obligations * @param definitions a set of <code>VariableDefinition</code> objects that must provide all * definitions referenced by all <code>VariableReference</code>s in the policy * @param parameters the <code>List</code> of <code>CombinerParameter</code>s provided for * general use by the combining algorithm * * @throws IllegalArgumentException if the <code>List</code> of rules contains an object that is * not a <code>RuleCombinerElement</code> */ public Policy(URI id, String version, RuleCombiningAlgorithm combiningAlg, String description, AbstractTarget target, String defaultVersion, List<CombinerElement> ruleElements, Set<AbstractObligation> obligations, Set<VariableDefinition> definitions, List<CombinerParameter> parameters) { super(id, version, combiningAlg, description, target, defaultVersion, obligations, null, parameters); // check that the list contains only RuleCombinerElements if (ruleElements != null) { for (Object o : ruleElements) { if (!(o instanceof RuleCombinerElement)){ throw new IllegalArgumentException("non-Rule in rules"); } } } setChildren(ruleElements); // save the definitions if (definitions == null) this.definitions = new HashSet<VariableDefinition>(); else this.definitions = Collections.unmodifiableSet(new HashSet<VariableDefinition>(definitions)); } /** * Creates a new Policy based on the given root node. This is private since every class is * supposed to use a getInstance() method to construct from a Node, but since we want some * common code in the parent class, we need this functionality in a constructor. * * @param root the node to parse for the <code>Policy</code> * the XACML policy, if null use default factories * @throws ParsingException ParsingException if the PolicyType is invalid */ private Policy(Node root) throws ParsingException { super(root, "Policy", "RuleCombiningAlgId"); List<Rule> rules = new ArrayList<Rule>(); HashMap<String, List<CombinerParameter>> parameters = new HashMap<String, List<CombinerParameter>>(); HashMap<String, Node> variableIds = new HashMap<String, Node>(); PolicyMetaData metaData = getMetaData(); // first off, go through and look for any definitions to get their // identifiers up front, since before we parse any references we'll // need to know what definitions we support NodeList children = root.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (DOMHelper.getLocalName(child).equals("VariableDefinition")) { String id = child.getAttributes().getNamedItem("VariableId").getNodeValue(); // it's an error to have more than one definition with the // same identifier if (variableIds.containsKey(id)) throw new ParsingException("multiple definitions for " + "variable " + id); variableIds.put(id, child); } } // now create a manager with the defined variable identifiers VariableManager manager = new VariableManager(variableIds, metaData); definitions = new HashSet<VariableDefinition>(); // next, collect the Policy-specific elements for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); String name = DOMHelper.getLocalName(child); if (name.equals("Rule")) { rules.add(Rule.getInstance(child, metaData, manager)); } else if (name.equals("RuleCombinerParameters")) { String ref = child.getAttributes().getNamedItem("RuleIdRef").getNodeValue(); // if we found the parameter before than add it the end of // the previous paramters, otherwise create a new entry if (parameters.containsKey(ref)) { List<CombinerParameter> list = parameters.get(ref); parseParameters(list, child); } else { List<CombinerParameter> list = new ArrayList<CombinerParameter>(); parseParameters(list, child); parameters.put(ref, list); } } else if (name.equals("VariableDefinition")) { String id = child.getAttributes().getNamedItem("VariableId").getNodeValue(); // parsing definitions is a little strange, since they can // contain references to definitions we haven't yet parsed // or circular references, but we still want to verify the // references and the types...so, for each definition, we // ask the manager though getDefinition, which takes care // of loading any forward references, handles loops, etc. // It also handles caching definitions, so we don't end // up parsing the same definitions multiple times definitions.add(manager.getDefinition(id)); } } definitions = Collections.unmodifiableSet(definitions); // now make sure that we can match up any parameters we may have // found to a corresponding Rule List<CombinerElement> elements = new ArrayList<CombinerElement>(); for (Rule rule : rules) { String id = rule.getId().toString(); List list = (List) (parameters.remove(id)); elements.add(new RuleCombinerElement(rule, list)); } // ...and that there aren't extra parameters if (!parameters.isEmpty()) throw new ParsingException("Unmatched parameters in Rule"); // finally, set the list of Rules setChildren(elements); } /** * Helper method that parses out a collection of combiner parameters. */ private void parseParameters(List<CombinerParameter> parameters, Node root) throws ParsingException { NodeList nodes = root.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (DOMHelper.getLocalName(node).equals("CombinerParameter")) parameters.add(CombinerParameter.getInstance(node)); } } /** * Creates an instance of a <code>Policy</code> object based on a DOM node. The node must be the * root of PolicyType XML object, otherwise an exception is thrown. * * @param root the DOM root of a PolicyType XML type * the XACML policy, if null use default factories * @return a <code>Policy</code> object * @throws ParsingException if the PolicyType is invalid */ public static Policy getInstance(Node root) throws ParsingException { // first off, check that it's the right kind of node if (!DOMHelper.getLocalName(root).equals("Policy")) { throw new ParsingException("Cannot create Policy from root of " + "type " + DOMHelper.getLocalName(root)); } return new Policy(root); } /** * Returns the variable definitions in this Policy. * * @return a <code>Set</code> of <code>VariableDefinition</code>s */ public Set getVariableDefinitions() { return definitions; } /** * Encodes this <code>Policy</code> into its XML form * * @return <code>String</code> */ public String encode() { StringBuilder builder = new StringBuilder(); encode(builder); return builder.toString(); } /** * Encodes this <code>Policy</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) { String xacmlVersionId = metaData.getXACMLIdentifier(); String version = getVersion(); builder.append("<Policy xmlns=\"").append(xacmlVersionId).append("\" PolicyId=\"").append(getId().toString()). append("\" Version=\"").append(version).append("\" RuleCombiningAlgId=\""). append(getCombiningAlg().getIdentifier().toString()).append("\">\n"); String description = getDescription(); if (description != null){ builder.append("<Description>").append(description).append("</Description>\n"); } String xPathVersion = metaData.getXPathIdentifier(); if (xPathVersion != null){ builder.append("<PolicyDefaults><XPathVersion>"). append(xPathVersion).append("</XPathVersion></PolicyDefaults>\n"); } getTarget().encode(builder); for (VariableDefinition definition : definitions) { definition.encode(builder); } encodeCommonElements(builder); builder.append("</Policy>\n"); } }
20,108
44.392777
118
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/MatchResult.java
/* * @(#)MatchResult.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana; import org.wso2.balana.ctx.Status; /** * This is used as the return value for the various target matching functions. It communicates that * either the target matches the input request, the target doesn't match the input request, or the * result is Indeterminate. * * @since 1.0 * @author Seth Proctor */ public class MatchResult { /** * An integer value indicating the the target matches the request */ public static final int MATCH = 0; /** * An integer value indicating that the target doesn't match the request */ public static final int NO_MATCH = 1; /** * An integer value indicating the the result is Indeterminate */ public static final int INDETERMINATE = 2; // private int result; private Status status; private String policyValue; private String subjectPolicyValue; private String resourcePolicyValue; private String actionPolicyValue; private String envPolicyValue; public String getSubjectPolicyValue() { return subjectPolicyValue; } public void setSubjectPolicyValue(String subjectPolicyValue) { this.subjectPolicyValue = subjectPolicyValue; } public String getResourcePolicyValue() { return resourcePolicyValue; } public void setResourcePolicyValue(String resourcePolicyValue) { this.resourcePolicyValue = resourcePolicyValue; } public String getActionPolicyValue() { return actionPolicyValue; } public void setActionPolicyValue(String actionPolicyValue) { this.actionPolicyValue = actionPolicyValue; } public String getEnvPolicyValue() { return envPolicyValue; } public void setEnvPolicyValue(String envPolicyValue) { this.envPolicyValue = envPolicyValue; } public String getPolicyValue() { return policyValue; } public void setPolicyValue(String policyValue) { this.policyValue = policyValue; } /** * Constructor that creates a <code>MatchResult</code> with no Status * * @param result the applicable result */ public MatchResult(int result) { this(result, null); } /** * 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; } /** * Returns the applicable result * * @return the applicable result */ public int getResult() { return result; } /** * Returns the status if there was an error, or null if no error occurred * * @return the error status data or null */ public Status getStatus() { return status; } }
5,075
30.52795
99
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/DOMHelper.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana; import org.w3c.dom.Document; import org.w3c.dom.Node; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.ByteArrayInputStream; /** * This class is created for patch provided in IDENTITY-416 * * XML parsing via DOM API the method node.getLocalName() or getNodeName() is used. But not all parsed * nodes are elements or attribute. to support namespaces it is needed to either access via node.getLocalName() * or DOMHelper.getLocalName(node) depending on the node type. */ public class DOMHelper { public static String getLocalName(Node child) { String localName = child.getLocalName(); if (localName == null) return child.getNodeName(); return localName; } }
1,471
31
112
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/AbstractTarget.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana; import org.wso2.balana.ctx.EvaluationCtx; import java.io.OutputStream; /** * Represents the TargetType XML type in XACML. This defined as abstract, because there can be * more than one implementation of TargetType. As an example, TargetType is considerably defer in * XACML 2.0 and XACML 3.0 Therefore two implementations are used. * * The target is used to quickly identify whether the parent element (a policy set, policy, or rule) * is applicable to a given request. */ public abstract class AbstractTarget { /** * Determines whether this <code>AbstractTarget</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 abstract MatchResult match(EvaluationCtx context); /** * Encodes this <code>AbstractTarget</code> into its XML form * * @return <code>String</code> */ public abstract String encode(); /** * Encodes this <code>AbstractTarget</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 abstract void encode(StringBuilder builder); }
2,005
31.885246
101
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/CombiningAlgFactoryProxy.java
/* * @(#)CombiningAlgFactoryProxy.java * * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.combine; /** * A simple proxy interface used to install new <code>CombiningAlgFactory</code>s. * * @since 1.2 * @author Seth Proctor */ public interface CombiningAlgFactoryProxy { /** * Returns an instance of the <code>CombiningAlgFactory</code> for which this is a proxy. * * @return a <code>CombiningAlgFactory</code> instance */ public CombiningAlgFactory getFactory(); }
2,264
40.944444
93
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/RuleCombiningAlgorithm.java
/* * @(#)RuleCombiningAlgorithm.java * * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.combine; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.ctx.AbstractResult; import java.net.URI; import java.util.List; /** * The base type for all Rule combining algorithms. * * @since 1.0 * @author Seth Proctor * @author Marco Barreno */ public abstract class RuleCombiningAlgorithm extends CombiningAlgorithm { /** * Constructor that takes the algorithm's identifier. * * @param identifier the algorithm's identifier */ public RuleCombiningAlgorithm(URI identifier) { super(identifier); } /** * Combines the rules based on the context to produce some unified result. This is the one * function of a combining algorithm. * * @param context the representation of the request * @param parameters a (possibly empty) non-null <code>List</code> of * <code>CombinerParameter<code>s * @param ruleElements a <code>List</code> of <code>CombinerElement<code>s * * @return a single unified result based on the combining logic */ public abstract AbstractResult combine(EvaluationCtx context, List parameters, List ruleElements); }
3,020
37.730769
102
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/BaseCombiningAlgFactory.java
/* * @(#)BaseCombiningAlgFactory.java * * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.combine; import org.wso2.balana.UnknownIdentifierException; import java.net.URI; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Set; /** * This is a basic implementation of <code>CombiningAlgFactory</code>. It implements the insertion * and retrieval methods, but doesn't actually setup the factory with any algorithms. * <p> * Note that while this class is thread-safe on all creation methods, it is not safe to add support * for a new algorithm while creating an instance of an algorithm. This follows from the assumption * that most people will initialize these factories up-front, and then start processing without ever * modifying the factories. If you need these mutual operations to be thread-safe, then you should * write a wrapper class that implements the right synchronization. * * @since 1.2 * @author Seth Proctor */ public class BaseCombiningAlgFactory extends CombiningAlgFactory { // the map of available combining algorithms private HashMap algMap; /** * Default constructor. */ public BaseCombiningAlgFactory() { algMap = new HashMap(); } /** * Constructor that configures this factory with an initial set of supported algorithms. * * @param algorithms a <code>Set</code> of </code>CombiningAlgorithm</code>s * * @throws IllegalArgumentException if any elements of the set are not * </code>CombiningAlgorithm</code>s */ public BaseCombiningAlgFactory(Set algorithms) { algMap = new HashMap(); Iterator it = algorithms.iterator(); while (it.hasNext()) { try { CombiningAlgorithm alg = (CombiningAlgorithm) (it.next()); algMap.put(alg.getIdentifier().toString(), alg); } catch (ClassCastException cce) { throw new IllegalArgumentException("an element of the set " + "was not an instance of " + "CombiningAlgorithm"); } } } /** * Adds a combining algorithm to the factory. This single instance will be returned to anyone * who asks the factory for an algorithm with the id given here. * * @param alg the combining algorithm to add * * @throws IllegalArgumentException if the algId is already registered */ public void addAlgorithm(CombiningAlgorithm alg) { String algId = alg.getIdentifier().toString(); // check that the id doesn't already exist in the factory if (algMap.containsKey(algId)) throw new IllegalArgumentException("algorithm already registered: " + algId); // add the algorithm algMap.put(algId, alg); } /** * Returns the algorithm identifiers supported by this factory. * * @return a <code>Set</code> of <code>String</code>s */ public Set getSupportedAlgorithms() { return Collections.unmodifiableSet(algMap.keySet()); } /** * Tries to return the correct combinging algorithm based on the given algorithm ID. * * @param algId the identifier by which the algorithm is known * * @return a combining algorithm * * @throws UnknownIdentifierException algId is unknown */ public CombiningAlgorithm createAlgorithm(URI algId) throws UnknownIdentifierException { String id = algId.toString(); if (algMap.containsKey(id)) { return (CombiningAlgorithm) (algMap.get(algId.toString())); } else { throw new UnknownIdentifierException("unknown combining algId: " + id); } } }
5,515
37.573427
100
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/PolicyCombinerElement.java
/* * @(#)PolicyCombinerElement.java * * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.combine; import org.wso2.balana.AbstractPolicy; import org.wso2.balana.Indenter; import org.wso2.balana.Policy; import org.wso2.balana.PolicyReference; import org.wso2.balana.PolicySet; import java.io.OutputStream; import java.io.PrintStream; import java.util.Iterator; import java.util.List; /** * Specific version of <code>CombinerElement</code> used for policy combining. * * @since 2.0 * @author Seth Proctor */ public class PolicyCombinerElement extends CombinerElement { /** * Constructor that only takes an <code>AbstractPolicy</code. No parameters are associated with * this <code>AbstractPolicy</code> when combining. * * @param policy an <code>AbstractPolicy</code> to use in combining */ public PolicyCombinerElement(AbstractPolicy policy) { super(policy); } /** * Constructor that takes both the <code>AbstractPolicy</code> to combine and its associated * combiner parameters. * * @param policy an <code>AbstractPolicy</code> to use in combining * @param parameters a (possibly empty) non-null <code>List</code> of * <code>CombinerParameter<code>s provided for general * use (for all pre-2.0 policies this must be empty) */ public PolicyCombinerElement(AbstractPolicy policy, List parameters) { super(policy, parameters); } /** * Returns the <code>AbstractPolicy</code> in this element. * * @return the element's <code>AbstractPolicy</code> */ public AbstractPolicy getPolicy() { return (AbstractPolicy) (getElement()); } /** * Encodes this <code>PolicyCombinerElement</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) { if (!getParameters().isEmpty()) { AbstractPolicy policy = getPolicy(); // FIXME: This is ugly and happens in several places...maybe this // should get folded into the AbstractPolicy API? if (policy instanceof Policy) { encodeParamaters(builder, "Policy", policy.getId().toString()); } else if (policy instanceof PolicySet) { encodeParamaters(builder, "PolicySet", policy.getId().toString()); } else { PolicyReference ref = (PolicyReference) policy; if (ref.getReferenceType() == PolicyReference.POLICY_REFERENCE) encodeParamaters(builder, "Policy", ref.getReference().toString()); else encodeParamaters(builder, "PolicySet", ref.getReference().toString()); } } getPolicy().encode(builder); } /** * Private helper that encodes the parameters based on the type * * @param builder * @param prefix * @param id */ private void encodeParamaters(StringBuilder builder, String prefix, String id) { Iterator it = getParameters().iterator(); builder.append("<").append(prefix).append("CombinerParameters "). append(prefix).append("IdRef=\"").append(id).append("\">\n"); while (it.hasNext()) { CombinerParameter param = (CombinerParameter) (it.next()); param.encode(builder); } builder.append("</").append(prefix).append("CombinerParameters>\n"); } }
5,367
37.342857
108
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/CombinerElement.java
/* * @(#)CombinerElement.java * * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.combine; import org.wso2.balana.Indenter; import org.wso2.balana.PolicyTreeElement; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.io.OutputStream; /** * Represents one input (a Rule, Policy, PolicySet, or reference) to a combining algorithm and * combiner parameters associated with that input. * * @since 2.0 * @author Seth Proctor */ public abstract class CombinerElement { // the element to be combined private PolicyTreeElement element; // the parameters used with this element private List parameters; /** * Constructor that only takes an element. No parameters are associated with this element when * combining. * * @param element a <code>PolicyTreeElement</code> to use in combining */ public CombinerElement(PolicyTreeElement element) { this(element, null); } /** * Constructor that takes both the element to combine and its associated combiner parameters. * * @param element a <code>PolicyTreeElement</code> to use in combining * @param parameters a (possibly empty) non-null <code>List</code> of * <code>CombinerParameter<code>s provided for general * use (for all pre-2.0 policies this must be empty) */ public CombinerElement(PolicyTreeElement element, List parameters) { this.element = element; if (parameters == null) this.parameters = Collections.unmodifiableList(new ArrayList()); else this.parameters = Collections.unmodifiableList(new ArrayList(parameters)); } /** * Returns the <code>PolicyTreeElement</code> in this element. * * @return the <code>PolicyTreeElement</code> */ public PolicyTreeElement getElement() { return element; } /** * Returns the <code>CombinerParameter</code>s associated with this element. * * @return a <code>List</code> of <code>CombinerParameter</code>s */ public List getParameters() { return parameters; } /** * Encodes this <code>CombinerElement</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 abstract void encode(StringBuilder builder); }
4,228
35.456897
102
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/StandardCombiningAlgFactory.java
/* * @(#)StandardCombiningAlgFactory.java * * Copyright 2004-2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.combine; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.balana.UnknownIdentifierException; import org.wso2.balana.XACMLConstants; import org.wso2.balana.combine.xacml2.*; import org.wso2.balana.combine.xacml3.DenyUnlessPermitPolicyAlg; import org.wso2.balana.combine.xacml3.DenyUnlessPermitRuleAlg; import org.wso2.balana.combine.xacml3.PermitUnlessDenyPolicyAlg; import org.wso2.balana.combine.xacml3.PermitUnlessDenyRuleAlg; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** * This factory supports the standard set of algorithms specified in XACML 1.x and 2.0. It is the * default factory used by the system, and imposes a singleton pattern insuring that there is only * ever one instance of this class. * <p> * Note that because this supports only the standard algorithms, this factory does not allow the * addition of any other algorithms. If you call <code>addAlgorithm</code> on an instance of this * class, an exception will be thrown. If you need a standard factory that is modifiable, you should * create a new <code>BaseCombiningAlgFactory</code> (or some other <code>CombiningAlgFactory</code> * ) and configure it with the standard algorithms using <code>getStandardAlgorithms</code> (or, in * the case of <code>BaseAttributeFactory</code>, by providing the datatypes in the constructor). * * @since 1.2 * @author Seth Proctor */ public class StandardCombiningAlgFactory extends BaseCombiningAlgFactory { // the single factory instance private static volatile StandardCombiningAlgFactory factoryInstance = null; // the algorithms supported by this factory private static Set supportedAlgorithms = null; // identifiers for the supported algorithms private static Set supportedAlgIds; // the logger we'll use for all messages private static final Log logger = LogFactory.getLog(StandardCombiningAlgFactory.class); /** * Default constructor. */ private StandardCombiningAlgFactory() { super(supportedAlgorithms); } /** * Private initializer for the supported algorithms. This isn't called until something needs * these values, and is only called once. */ private static void initAlgorithms() { if (logger.isDebugEnabled()) { logger.debug("Initializing standard combining algorithms"); } supportedAlgorithms = new HashSet(); supportedAlgIds = new HashSet(); supportedAlgorithms.add(new DenyOverridesRuleAlg()); supportedAlgIds.add(DenyOverridesRuleAlg.algId); supportedAlgorithms.add(new DenyOverridesPolicyAlg()); supportedAlgIds.add(DenyOverridesPolicyAlg.algId); supportedAlgorithms.add(new OrderedDenyOverridesRuleAlg()); supportedAlgIds.add(OrderedDenyOverridesRuleAlg.algId); supportedAlgorithms.add(new OrderedDenyOverridesPolicyAlg()); supportedAlgIds.add(OrderedDenyOverridesPolicyAlg.algId); supportedAlgorithms.add(new PermitOverridesRuleAlg()); supportedAlgIds.add(PermitOverridesRuleAlg.algId); supportedAlgorithms.add(new PermitOverridesPolicyAlg()); supportedAlgIds.add(PermitOverridesPolicyAlg.algId); supportedAlgorithms.add(new OrderedPermitOverridesRuleAlg()); supportedAlgIds.add(OrderedPermitOverridesRuleAlg.algId); supportedAlgorithms.add(new OrderedPermitOverridesPolicyAlg()); supportedAlgIds.add(OrderedPermitOverridesPolicyAlg.algId); supportedAlgorithms.add(new FirstApplicableRuleAlg()); supportedAlgIds.add(FirstApplicableRuleAlg.algId); supportedAlgorithms.add(new FirstApplicablePolicyAlg()); supportedAlgIds.add(FirstApplicablePolicyAlg.algId); supportedAlgorithms.add(new OnlyOneApplicablePolicyAlg()); supportedAlgIds.add(OnlyOneApplicablePolicyAlg.algId); // XACML 3.0 supportedAlgorithms.add(new DenyUnlessPermitRuleAlg()); supportedAlgIds.add(DenyUnlessPermitRuleAlg.algId); supportedAlgorithms.add(new DenyUnlessPermitPolicyAlg()); supportedAlgIds.add(DenyUnlessPermitPolicyAlg.algId); supportedAlgorithms.add(new PermitUnlessDenyRuleAlg()); supportedAlgIds.add(PermitUnlessDenyRuleAlg.algId); supportedAlgorithms.add(new PermitUnlessDenyPolicyAlg()); supportedAlgIds.add(PermitUnlessDenyPolicyAlg.algId); supportedAlgorithms.add(new org.wso2.balana.combine.xacml3.DenyOverridesRuleAlg()); supportedAlgIds.add(org.wso2.balana.combine.xacml3.DenyOverridesRuleAlg.algId); supportedAlgorithms.add(new org.wso2.balana.combine.xacml3.DenyOverridesPolicyAlg()); supportedAlgIds.add(org.wso2.balana.combine.xacml3.DenyOverridesPolicyAlg.algId); supportedAlgorithms.add(new org.wso2.balana.combine.xacml3.OrderedDenyOverridesRuleAlg()); supportedAlgIds.add(org.wso2.balana.combine.xacml3.OrderedDenyOverridesRuleAlg.algId); supportedAlgorithms.add(new org.wso2.balana.combine.xacml3.OrderedDenyOverridesPolicyAlg()); supportedAlgIds.add(org.wso2.balana.combine.xacml3.OrderedDenyOverridesPolicyAlg.algId); supportedAlgorithms.add(new org.wso2.balana.combine.xacml3.PermitOverridesRuleAlg()); supportedAlgIds.add(org.wso2.balana.combine.xacml3.PermitOverridesRuleAlg.algId); supportedAlgorithms.add(new org.wso2.balana.combine.xacml3.PermitOverridesPolicyAlg()); supportedAlgIds.add(org.wso2.balana.combine.xacml3.PermitOverridesPolicyAlg.algId); supportedAlgorithms.add(new org.wso2.balana.combine.xacml3.OrderedPermitOverridesRuleAlg()); supportedAlgIds.add(org.wso2.balana.combine.xacml3.OrderedPermitOverridesRuleAlg.algId); supportedAlgorithms.add(new org.wso2.balana.combine.xacml3.OrderedPermitOverridesPolicyAlg()); supportedAlgIds.add(org.wso2.balana.combine.xacml3.OrderedPermitOverridesPolicyAlg.algId); supportedAlgIds = Collections.unmodifiableSet(supportedAlgIds); } /** * Returns an instance of this factory. This method enforces a singleton model, meaning that * this always returns the same instance, creating the factory if it hasn't been requested * before. This is the default model used by the <code>CombiningAlgFactory</code>, ensuring * quick access to this factory. * * @return the factory instance */ public static StandardCombiningAlgFactory getFactory() { if (factoryInstance == null) { synchronized (StandardCombiningAlgFactory.class) { if (factoryInstance == null) { initAlgorithms(); factoryInstance = new StandardCombiningAlgFactory(); } } } return factoryInstance; } /** * A convenience method that returns a new instance of a <code>CombiningAlgFactory</code> that * supports all of the standard algorithms. The new factory allows adding support for new * algorithms. This method should only be used when you need a new, mutable instance (eg, when * you want to create a new factory that extends the set of supported algorithms). In general, * you should use <code>getFactory</code> which is more efficient and enforces a singleton * pattern. * * @return a new factory supporting the standard algorithms */ public static CombiningAlgFactory getNewFactory() { // first we make sure everything's been initialized... getFactory(); // ...then we create the new instance return new BaseCombiningAlgFactory(supportedAlgorithms); } /** * Returns the identifiers supported for the given version of XACML. Because this factory * supports identifiers from all versions of the XACML specifications, this method is useful for * getting a list of which specific identifiers are supported by a given version of XACML. * * @param xacmlVersion a standard XACML identifier string, as provided in * <code>PolicyMetaData</code> * * @return a <code>Set</code> of identifiers * * @throws UnknownIdentifierException if the version string is unknown */ public static Set getStandardAlgorithms(String xacmlVersion) throws UnknownIdentifierException { if (xacmlVersion.equals(XACMLConstants.XACML_1_0_IDENTIFIER) || xacmlVersion.equals(XACMLConstants.XACML_2_0_IDENTIFIER) || xacmlVersion.equals(XACMLConstants.XACML_3_0_IDENTIFIER)){ return supportedAlgIds; } throw new UnknownIdentifierException("Unknown XACML version: " + xacmlVersion); } /** * Throws an <code>UnsupportedOperationException</code> since you are not allowed to modify what * a standard factory supports. * * @param alg the combining algorithm to add * * @throws UnsupportedOperationException always */ public void addAlgorithm(CombiningAlgorithm alg) { throw new UnsupportedOperationException("a standard factory cannot " + "support new algorithms"); } }
11,060
45.47479
102
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/CombiningAlgorithm.java
/* * @(#)CombiningAlgorithm.java * * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.combine; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.ctx.AbstractResult; import java.net.URI; import java.util.List; /** * The base type for all combining algorithms. It provides one method that must be implemented. * * @since 1.0 * @author Seth Proctor */ public abstract class CombiningAlgorithm { // the identifier for the algorithm private URI identifier; /** * Constructor that takes the algorithm's identifier. * * @param identifier the algorithm's identifier */ public CombiningAlgorithm(URI identifier) { this.identifier = identifier; } /** * Combines the results of the inputs based on the context to produce some unified result. This * is the one function of a combining algorithm. * * @param context the representation of the request * @param parameters a (possibly empty) non-null <code>List</code> of * <code>CombinerParameter<code>s provided for general * use (for all pre-2.0 policies this must be empty) * @param inputs a <code>List</code> of <code>CombinerElements</code>s to evaluate and combine * * @return a single unified result based on the combining logic */ public abstract AbstractResult combine(EvaluationCtx context, List parameters, List inputs); /** * Returns the identifier for this algorithm. * * @return the algorithm's identifier */ public URI getIdentifier() { return identifier; } }
3,389
36.666667
99
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/PolicyCombiningAlgorithm.java
/* * @(#)PolicyCombiningAlgorithm.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.combine; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.ctx.AbstractResult; import java.net.URI; import java.util.List; /** * The base type for all Policy combining algorithms. Unlike in Rule Combining Algorithms, each * policy must be matched before they're evaluated to make sure they apply. Also, in combining * policies, obligations must be handled correctly. Specifically, no obligation may be included in * the <code>Result</code> that doesn't match the effect being returned. So, if INDETERMINATE or * NOT_APPLICABLE is the returned effect, no obligations may be included in the result. If the * effect of the combining algorithm is PERMIT or DENY, then obligations with a matching fulfillOn * effect are also included in the result. * * @since 1.0 * @author Seth Proctor * @author Marco Barreno */ public abstract class PolicyCombiningAlgorithm extends CombiningAlgorithm { /** * Constructor that takes the algorithm's identifier. * * @param identifier the algorithm's identifier */ public PolicyCombiningAlgorithm(URI identifier) { super(identifier); } /** * Combines the policies based on the context to produce some unified result. This is the one * function of a combining algorithm. * <p> * Note that unlike in the RuleCombiningAlgorithms, here you must explicitly match the * sub-policies to make sure that you should consider them, and you must handle Obligations. * * @param context the representation of the request * @param parameters a (possibly empty) non-null <code>List</code> of * <code>CombinerParameter<code>s * @param policyElements a <code>List</code> of <code>CombinerElement<code>s * * @return a single unified result based on the combining logic */ public abstract AbstractResult combine(EvaluationCtx context, List parameters, List policyElements); }
3,804
42.735632
104
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/CombinerParameter.java
/* * @(#)CombinerParameter.java * * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.combine; import org.wso2.balana.Balana; import org.wso2.balana.Indenter; import org.wso2.balana.ParsingException; import org.wso2.balana.UnknownIdentifierException; import org.wso2.balana.attr.AttributeFactory; import org.wso2.balana.attr.AttributeValue; import java.io.OutputStream; import java.io.PrintStream; import org.w3c.dom.Node; /** * Represents a single named parameter to a combining algorithm. Parameters are only used by XACML * 2.0 and later policies. * * @since 2.0 * @author Seth Proctor */ public class CombinerParameter { // the name of this parameter private String name; // the value of this parameter private AttributeValue value; /** * Creates a new CombinerParameter. * * @param name the parameter's name * @param value the parameter's value */ public CombinerParameter(String name, AttributeValue value) { this.name = name; this.value = value; } /** * Returns a new instance of the <code>CombinerParameter</code> class based on a DOM node. The * node must be the root of an XML CombinerParameterType. * * @param root the DOM root of a CombinerParameterType XML type * * @throws ParsingException if the CombinerParameterType is invalid * @return an instance of <code>CombinerParameter</code> */ public static CombinerParameter getInstance(Node root) throws ParsingException { // get the name, which is a required attribute String name = root.getAttributes().getNamedItem("ParameterName").getNodeValue(); // get the attribute value, the only child of this element AttributeFactory attrFactory = Balana.getInstance().getAttributeFactory(); AttributeValue value = null; try { value = attrFactory.createValue(root.getFirstChild()); } catch (UnknownIdentifierException uie) { throw new ParsingException(uie.getMessage(), uie); } return new CombinerParameter(name, value); } /** * Returns the name of this parameter. * * @return the name of this parameter */ public String getName() { return name; } /** * Returns the value provided by this parameter. * * @return the value provided by this parameter */ public AttributeValue getValue() { return value; } /** * Encodes this <code>CombinerParameter</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("<CombinerParameter ParameterName=\"").append(getName()).append("\">\n"); getValue().encode(builder); builder.append("</CombinerParameter>\n"); } }
4,722
33.474453
104
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/RuleCombinerElement.java
/* * @(#)RuleCombinerElement.java * * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.combine; import org.wso2.balana.Indenter; import org.wso2.balana.Rule; import java.io.OutputStream; import java.io.PrintStream; import java.util.Iterator; import java.util.List; /** * Specific version of <code>CombinerElement</code> used for rule combining. * * @since 2.0 * @author Seth Proctor */ public class RuleCombinerElement extends CombinerElement { /** * Constructor that only takes a <code>Rule</code. No parameters are associated with this * <code>Rule</code> when combining. * * @param rule a <code>Rule</code> to use in combining */ public RuleCombinerElement(Rule rule) { super(rule); } /** * Constructor that takes both the <code>Rule</code> to combine and its associated combiner * parameters. * * @param rule a <code>Rule</code> to use in combining * @param parameters a (possibly empty) non-null <code>List</code> of * <code>CombinerParameter<code>s provided for general * use (for all pre-2.0 policies this must be empty) */ public RuleCombinerElement(Rule rule, List parameters) { super(rule, parameters); } /** * Returns the <code>Rule</code> in this element. * * @return the element's <code>Rule</code> */ public Rule getRule() { return (Rule) (getElement()); } /** * Encodes this <code>RuleCombinerElement</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) { Iterator it = getParameters().iterator(); if (it.hasNext()) { builder.append("<RuleCombinerParameters RuleIdRef=\"").append(getRule().getId()).append("\">\n"); while (it.hasNext()) { CombinerParameter param = (CombinerParameter) (it.next()); param.encode(builder); } builder.append("</RuleCombinerParameters>\n"); } getRule().encode(builder); } }
3,978
35.172727
109
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/CombiningAlgFactory.java
/* * @(#)CombiningAlgFactory.java * * Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.combine; import org.wso2.balana.PolicyMetaData; import org.wso2.balana.UnknownIdentifierException; import org.wso2.balana.XACMLConstants; import java.net.URI; import java.util.HashMap; import java.util.Set; /** * Provides a factory mechanism for installing and retrieving combining algorithms. * * @since 1.0 * @author Seth Proctor */ public abstract class CombiningAlgFactory { // the proxy used to get the default factory private static CombiningAlgFactoryProxy defaultFactoryProxy; // the map of registered factories private static HashMap<String, CombiningAlgFactoryProxy> registeredFactories; /** * static initializer that sets up the default factory proxy and registers the standard * namespaces */ static { CombiningAlgFactoryProxy proxy = new CombiningAlgFactoryProxy() { public CombiningAlgFactory getFactory() { return StandardCombiningAlgFactory.getFactory(); } }; registeredFactories = new HashMap<String, CombiningAlgFactoryProxy>(); registeredFactories.put(XACMLConstants.XACML_1_0_IDENTIFIER, proxy); registeredFactories.put(XACMLConstants.XACML_2_0_IDENTIFIER, proxy); registeredFactories.put(XACMLConstants.XACML_3_0_IDENTIFIER, proxy); defaultFactoryProxy = proxy; }; /** * Default constructor. Used only by subclasses. */ protected CombiningAlgFactory() { } /** * Returns the default factory. Depending on the default factory's implementation, this may * return a singleton instance or new instances with each invocation. * * @return the default <code>CombiningAlgFactory</code> */ public static final CombiningAlgFactory getInstance() { return defaultFactoryProxy.getFactory(); } /** * Returns a factory based on the given identifier. You may register as many factories as you * like, and then retrieve them through this interface, but a factory may only be registered * once using a given identifier. By default, the standard XACML 1.0 2.0 and 3.0 identifiers are * registered to provide the standard factory. * * @param identifier the identifier for a factory * * @return a <code>CombiningAlgFactory</code> * * @throws UnknownIdentifierException if the given identifier isn't registered */ public static final CombiningAlgFactory getInstance(String identifier) throws UnknownIdentifierException { CombiningAlgFactoryProxy proxy = registeredFactories.get(identifier); if (proxy == null) { throw new UnknownIdentifierException("Unknown CombiningAlgFactory " + "identifier: " + identifier); } return proxy.getFactory(); } /** * Sets the default factory. This does not register the factory proxy as an identifiable * factory. * * @param proxy the <code>CombiningAlgFactoryProxy</code> to set as the new default factory * proxy */ public static final void setDefaultFactory(CombiningAlgFactoryProxy proxy) { defaultFactoryProxy = proxy; } /** * Registers the given factory proxy with the given identifier. If the identifier is already * used, then this throws an exception. If the identifier is not already used, then it will * always be bound to the given proxy. * * @param identifier the identifier for the proxy * @param proxy the <code>CombiningAlgFactoryProxy</code> to register with the given identifier * * @throws IllegalArgumentException if the identifier is already used */ public static final void registerFactory(String identifier, CombiningAlgFactoryProxy proxy) throws IllegalArgumentException { synchronized (registeredFactories) { if (registeredFactories.containsKey(identifier)) throw new IllegalArgumentException("Identifier is already " + "registered as " + "CombiningAlgFactory: " + identifier); registeredFactories.put(identifier, proxy); } } /** * Adds a combining algorithm to the factory. This single instance will be returned to anyone * who asks the factory for an algorithm with the id given here. * * @param alg the combining algorithm to add * * @throws IllegalArgumentException if the algorithm is already registered */ public abstract void addAlgorithm(CombiningAlgorithm alg); /** * Adds a combining algorithm to the factory. This single instance will be returned to anyone * who asks the factory for an algorithm with the id given here. * * @deprecated As of version 1.2, replaced by {@link #addAlgorithm(CombiningAlgorithm)}. The new * factory system requires you to get a factory instance and then call the * non-static methods on that factory. The static versions of these methods have * been left in for now, but are slower and will be removed in a future version. * * @param alg the combining algorithm to add * * @throws IllegalArgumentException if the algorithm is already registered */ public static void addCombiningAlg(CombiningAlgorithm alg) { getInstance().addAlgorithm(alg); } /** * Returns the algorithm identifiers supported by this factory. * * @return a <code>Set</code> of <code>String</code>s */ public abstract Set getSupportedAlgorithms(); /** * Tries to return the correct combinging algorithm based on the given algorithm ID. * * @param algId the identifier by which the algorithm is known * * @return a combining algorithm * * @throws UnknownIdentifierException algId is unknown */ public abstract CombiningAlgorithm createAlgorithm(URI algId) throws UnknownIdentifierException; /** * Tries to return the correct combinging algorithm based on the given algorithm ID. * * @deprecated As of version 1.2, replaced by {@link #createAlgorithm(URI)}. The new factory * system requires you to get a factory instance and then call the non-static * methods on that factory. The static versions of these methods have been left in * for now, but are slower and will be removed in a future version. * * @param algId the identifier by which the algorithm is known * * @return a combining algorithm * * @throws UnknownIdentifierException algId is unknown */ public static CombiningAlgorithm createCombiningAlg(URI algId) throws UnknownIdentifierException { return getInstance().createAlgorithm(algId); } }
8,693
39.064516
100
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/xacml3/PermitUnlessDenyPolicyAlg.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.combine.xacml3; import org.wso2.balana.AbstractPolicy; import org.wso2.balana.MatchResult; import org.wso2.balana.ObligationResult; import org.wso2.balana.combine.PolicyCombinerElement; import org.wso2.balana.ctx.ResultFactory; import org.wso2.balana.Rule; import org.wso2.balana.combine.PolicyCombiningAlgorithm; import org.wso2.balana.combine.RuleCombinerElement; import org.wso2.balana.ctx.AbstractResult; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.xacml3.Advice; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * This is the standard Deny unless permit policy combining algorithm. This algorithm is intended for * those cases where a deny decision should have priority over a permit decision, and an "Indeterminate" or * "NotApplicable" must never be the result. It is particularly useful at the top level * in a policy structure to ensure that a PDP will always return a definite "Permit" or "Deny" result. */ public class PermitUnlessDenyPolicyAlg extends PolicyCombiningAlgorithm{ /** * The standard URI used to identify this algorithm */ public static final String algId = "urn:oasis:names:tc:xacml:3.0:policy-combining-algorithm:" + "permit-unless-deny"; // a URI form of the identifier private static URI identifierURI; // exception if the URI was invalid, which should never be a problem private static RuntimeException earlyException; static { try { identifierURI = new URI(algId); } catch (URISyntaxException se) { earlyException = new IllegalArgumentException(); earlyException.initCause(se); } } /** * Standard constructor. */ public PermitUnlessDenyPolicyAlg() { super(identifierURI); if (earlyException != null){ throw earlyException; } } /** * Constructor that takes the algorithm's identifier. * * @param identifier the algorithm's identifier */ public PermitUnlessDenyPolicyAlg(URI identifier) { super(identifier); } @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); } }
4,246
34.991525
107
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/xacml3/OrderedPermitOverridesRuleAlg.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.combine.xacml3; import java.net.URI; import java.net.URISyntaxException; /** * This is the new (XACML 3.0) standard Ordered Permit Overrides rule combining algorithm. * It allows a single evaluation of Permit to take precedence over any number of deny, * not applicable or indeterminate results. Note that this uses the regular Permit Overrides * implementation since it is also ordered. * */ public class OrderedPermitOverridesRuleAlg extends PermitOverridesRuleAlg { /** * The standard URN used to identify this algorithm */ public static final String algId = "urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:" + "ordered-permit-overrides"; // a URI form of the identifier private static URI identifierURI; // exception if the URI was invalid, which should never be a problem private static RuntimeException earlyException; static { try { identifierURI = new URI(algId); } catch (URISyntaxException se) { earlyException = new IllegalArgumentException(); earlyException.initCause(se); } } /** * Standard constructor. */ public OrderedPermitOverridesRuleAlg() { super(identifierURI); if (earlyException != null){ throw earlyException; } } }
2,014
30.484375
95
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/xacml3/PermitOverridesPolicyAlg.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.combine.xacml3; import org.wso2.balana.AbstractPolicy; import org.wso2.balana.MatchResult; import org.wso2.balana.ObligationResult; import org.wso2.balana.ctx.ResultFactory; import org.wso2.balana.combine.PolicyCombinerElement; import org.wso2.balana.combine.PolicyCombiningAlgorithm; import org.wso2.balana.ctx.AbstractResult; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.xacml3.Advice; import java.net.URI; import java.net.URISyntaxException; import java.util.*; /** * This is the new (XACML 3.0) is the standard Permit Overrides policy combining algorithm. It allows a single evaluation * of Permit to take precedence over any number of deny, not applicable or indeterminate results. * Note that since this implementation does an ordered evaluation, this class also supports the * Ordered Permit Overrides algorithm. */ public class PermitOverridesPolicyAlg extends PolicyCombiningAlgorithm{ /** * The standard URN used to identify this algorithm */ public static final String algId = "urn:oasis:names:tc:xacml:3.0:policy-combining-algorithm:" + "permit-overrides"; // a URI form of the identifier private static URI identifierURI; // exception if the URI was invalid, which should never be a problem private static RuntimeException earlyException; static { try { identifierURI = new URI(algId); } catch (URISyntaxException se) { earlyException = new IllegalArgumentException(); earlyException.initCause(se); } } /** * Standard constructor. */ public PermitOverridesPolicyAlg() { super(identifierURI); if (earlyException != null) throw earlyException; } /** * Protected constructor used by the ordered version of this algorithm. * * @param identifier the algorithm's identifier */ protected PermitOverridesPolicyAlg(URI identifier) { super(identifier); } /** * 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 atLeastOneErrorD = false; boolean atLeastOneErrorP = false; boolean atLeastOneErrorDP = false; boolean atLeastOneDeny = false; AbstractResult firstIndeterminateResultD = null; AbstractResult firstIndeterminateResultP = null; AbstractResult firstIndeterminateResultDP = null; List<ObligationResult> denyObligations = new ArrayList<ObligationResult>(); List<Advice> denyAdvices = 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) { // atLeastOneError = true; // // TODO // // 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 value = result.getDecision(); 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; } } else if(value == AbstractResult.DECISION_INDETERMINATE_DENY_OR_PERMIT){ atLeastOneErrorDP = true; // there are no rules about what to do if multiple cases // cause errors, so we'll just return the first one if(firstIndeterminateResultDP == null){ firstIndeterminateResultDP = result; } } } } } if (atLeastOneErrorDP) { return firstIndeterminateResultDP; } 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 (atLeastOneErrorD) { return ResultFactory.getFactory().getResult(AbstractResult.DECISION_INDETERMINATE_DENY, firstIndeterminateResultD.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); } }
7,884
38.823232
121
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/xacml3/OrderedDenyOverridesRuleAlg.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.combine.xacml3; import java.net.URI; import java.net.URISyntaxException; /** * This is the new (XACML 3.0)standard Ordered Deny Overrides rule combining algorithm. It allows * a single evaluation of Deny to take precedence over any number of permit, not applicable or * indeterminate results. Note that this uses the regular Deny Overrides implementation since it is also ordered. */ public class OrderedDenyOverridesRuleAlg extends DenyOverridesRuleAlg { /** * The standard URN used to identify this algorithm */ public static final String algId = "urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:" + "ordered-deny-overrides"; // a URI form of the identifier private static URI identifierURI; // exception if the URI was invalid, which should never be a problem private static RuntimeException earlyException; static { try { identifierURI = new URI(algId); } catch (URISyntaxException se) { earlyException = new IllegalArgumentException(); earlyException.initCause(se); } } /** * Standard constructor. */ public OrderedDenyOverridesRuleAlg() { super(identifierURI); if (earlyException != null){ throw earlyException; } } }
1,995
31.193548
113
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/xacml3/DenyUnlessPermitRuleAlg.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.combine.xacml3; import org.wso2.balana.ObligationResult; import org.wso2.balana.ctx.ResultFactory; import org.wso2.balana.Rule; import org.wso2.balana.combine.RuleCombinerElement; import org.wso2.balana.combine.RuleCombiningAlgorithm; import org.wso2.balana.ctx.AbstractResult; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.xacml3.Advice; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * This is the standard Deny unless permit rule combining algorithm. This algorithm is intended for * those cases where a permit decision should have priority over a deny decision, * and an "Indeterminate" or "NotApplicable" must never be the result. * It is particularly useful at the top level in a policy structure to ensure that a * PDP will always return a definite "Permit" or "Deny" result. */ public class DenyUnlessPermitRuleAlg extends RuleCombiningAlgorithm { /** * The standard URN used to identify this algorithm */ public static final String algId = "urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:" + "deny-unless-permit"; // a URI form of the identifier private static URI identifierURI; // exception if the URI was invalid, which should never be a problem private static RuntimeException earlyException; static { try { identifierURI = new URI(algId); } catch (URISyntaxException se) { earlyException = new IllegalArgumentException(); earlyException.initCause(se); } } /** * Standard constructor. */ public DenyUnlessPermitRuleAlg() { super(identifierURI); if (earlyException != null){ throw earlyException; } } /** * Constructor that takes the algorithm's identifier. * * @param identifier the algorithm's identifier */ public DenyUnlessPermitRuleAlg(URI identifier) { super(identifier); } @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); } }
3,933
33.814159
99
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/xacml3/OrderedDenyOverridesPolicyAlg.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.combine.xacml3; import java.net.URI; import java.net.URISyntaxException; /** * This is the new (XACML 3.0) standard Ordered Deny Overrides policy combining algorithm. It allows * a single evaluation of Deny to take precedence over any number of permit, not applicable or indeterminate * results. Note that this uses the regular Deny Overrides implementation since it is also ordered. */ public class OrderedDenyOverridesPolicyAlg extends DenyOverridesPolicyAlg { /** * The standard URN used to identify this algorithm */ public static final String algId = "urn:oasis:names:tc:xacml:3.0:policy-combining-algorithm:" + "ordered-deny-overrides"; // a URI form of the identifier private static URI identifierURI; // exception if the URI was invalid, which should never be a problem private static RuntimeException earlyException; static { try { identifierURI = new URI(algId); } catch (URISyntaxException se) { earlyException = new IllegalArgumentException(); earlyException.initCause(se); } } /** * Standard constructor. */ public OrderedDenyOverridesPolicyAlg() { super(identifierURI); if (earlyException != null){ throw earlyException; } } }
2,007
30.873016
108
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/xacml3/DenyUnlessPermitPolicyAlg.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.combine.xacml3; import org.wso2.balana.AbstractPolicy; import org.wso2.balana.MatchResult; import org.wso2.balana.ObligationResult; import org.wso2.balana.ctx.ResultFactory; import org.wso2.balana.combine.PolicyCombinerElement; import org.wso2.balana.combine.PolicyCombiningAlgorithm; import org.wso2.balana.ctx.AbstractResult; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.xacml3.Advice; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * This is the standard Deny unless permit policy combining algorithm. This algorithm is intended for * those cases where a permit decision should have priority over a deny decision, * and an "Indeterminate" or "NotApplicable" must never be the result. * It is particularly useful at the top level in a policy structure to ensure that a * PDP will always return a definite "Permit" or "Deny" result. */ public class DenyUnlessPermitPolicyAlg extends PolicyCombiningAlgorithm{ /** * The standard URN used to identify this algorithm */ public static final String algId = "urn:oasis:names:tc:xacml:3.0:policy-combining-algorithm:" + "deny-unless-permit"; // a URI form of the identifier private static URI identifierURI; // exception if the URI was invalid, which should never be a problem private static RuntimeException earlyException; static { try { identifierURI = new URI(algId); } catch (URISyntaxException se) { earlyException = new IllegalArgumentException(); earlyException.initCause(se); } } /** * Standard constructor. */ public DenyUnlessPermitPolicyAlg() { super(identifierURI); if (earlyException != null){ throw earlyException; } } @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); } }
3,954
36.311321
101
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/xacml3/OrderedPermitOverridesPolicyAlg.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.combine.xacml3; import java.net.URI; import java.net.URISyntaxException; /** * This is the new (XACML 3.0) standard Ordered Permit Overrides policy combining algorithm. * It allows a single evaluation of Permit to take precedence over any number of deny, * not applicable or indeterminate results. Note that this uses the regular Permit Overrides * implementation since it is also ordered. * */ public class OrderedPermitOverridesPolicyAlg extends PermitOverridesPolicyAlg { /** * The standard URN used to identify this algorithm */ public static final String algId = "urn:oasis:names:tc:xacml:3.0:policy-combining-algorithm:" + "ordered-permit-overrides"; // a URI form of the identifier private static URI identifierURI; // exception if the URI was invalid, which should never be a problem private static RuntimeException earlyException; static { try { identifierURI = new URI(algId); } catch (URISyntaxException se) { earlyException = new IllegalArgumentException(); earlyException.initCause(se); } } /** * Standard constructor. */ public OrderedPermitOverridesPolicyAlg() { super(identifierURI); if (earlyException != null){ throw earlyException; } } }
2,023
31.126984
97
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/xacml3/DenyOverridesRuleAlg.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.combine.xacml3; import org.wso2.balana.ObligationResult; import org.wso2.balana.ctx.ResultFactory; import org.wso2.balana.Rule; import org.wso2.balana.combine.RuleCombinerElement; import org.wso2.balana.combine.RuleCombiningAlgorithm; import org.wso2.balana.ctx.AbstractResult; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.xacml3.Advice; import java.net.URI; import java.net.URISyntaxException; import java.util.*; /** * This is the new (XACML 3.0) standard Deny Overrides rule combining algorithm. * It allows a single evaluation of Deny to take precedence over any number of permit, not applicable * or indeterminate results. Note that since this implementation does an ordered evaluation, * this class also supports the Ordered Deny Overrides algorithm. */ public class DenyOverridesRuleAlg extends RuleCombiningAlgorithm { /** * The standard URN used to identify this algorithm */ public static final String algId = "urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:" + "deny-overrides"; // a URI form of the identifier private static URI identifierURI; // exception if the URI was invalid, which should never be a problem private static RuntimeException earlyException; static { try { identifierURI = new URI(algId); } catch (URISyntaxException se) { earlyException = new IllegalArgumentException(); earlyException.initCause(se); } } /** * Standard constructor. */ public DenyOverridesRuleAlg() { super(identifierURI); if (earlyException != null){ throw earlyException; } } /** * Protected constructor used by the ordered version of this algorithm. * * @param identifier the algorithm's identifier */ protected DenyOverridesRuleAlg(URI identifier) { super(identifier); } /** * 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); } }
6,643
37.404624
109
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/xacml3/PermitOverridesRuleAlg.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.combine.xacml3; import org.wso2.balana.ObligationResult; import org.wso2.balana.ctx.ResultFactory; import org.wso2.balana.Rule; import org.wso2.balana.combine.RuleCombinerElement; import org.wso2.balana.combine.RuleCombiningAlgorithm; import org.wso2.balana.ctx.AbstractResult; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.xacml3.Advice; import java.net.URI; import java.net.URISyntaxException; import java.util.*; /** * This is the new (XACML 3.0) the standard Permit Overrides rule combining algorithm. It allows a single evaluation of * Permit to take precedence over any number of deny, not applicable or indeterminate results. Note * that since this implementation does an ordered evaluation, this class also supports the Ordered * Permit Overrides algorithm. */ public class PermitOverridesRuleAlg extends RuleCombiningAlgorithm{ /** * The standard URN used to identify this algorithm */ public static final String algId = "urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:" + "permit-overrides"; // a URI form of the identifier private static URI identifierURI; // exception if the URI was invalid, which should never be a problem private static RuntimeException earlyException; static { try { identifierURI = new URI(algId); } catch (URISyntaxException se) { earlyException = new IllegalArgumentException(); earlyException.initCause(se); } } /** * Standard constructor. */ public PermitOverridesRuleAlg() { super(identifierURI); if (earlyException != null) throw earlyException; } /** * Protected constructor used by the ordered version of this algorithm. * * @param identifier the algorithm's identifier */ protected PermitOverridesRuleAlg(URI identifier) { super(identifier); } /** * 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); } }
6,373
36.715976
119
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/xacml3/PermitUnlessDenyRuleAlg.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.combine.xacml3; import org.wso2.balana.ObligationResult; import org.wso2.balana.ctx.ResultFactory; import org.wso2.balana.Rule; import org.wso2.balana.combine.RuleCombinerElement; import org.wso2.balana.combine.RuleCombiningAlgorithm; import org.wso2.balana.ctx.AbstractResult; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.xacml3.Advice; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * This is the standard Deny unless permit rule combining algorithm. This algorithm is intended for * those cases where a deny decision should have priority over a permit decision, and an "Indeterminate" or * "NotApplicable" must never be the result. It is particularly useful at the top level * in a policy structure to ensure that a PDP will always return a definite "Permit" or "Deny" result. */ public class PermitUnlessDenyRuleAlg extends RuleCombiningAlgorithm{ /** * The standard URI used to identify this algorithm */ public static final String algId = "urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:" + "permit-unless-deny"; // a URI form of the identifier private static URI identifierURI; // exception if the URI was invalid, which should never be a problem private static RuntimeException earlyException; static { try { identifierURI = new URI(algId); } catch (URISyntaxException se) { earlyException = new IllegalArgumentException(); earlyException.initCause(se); } } /** * Standard constructor. */ public PermitUnlessDenyRuleAlg() { super(identifierURI); if (earlyException != null){ throw earlyException; } } /** * Constructor that takes the algorithm's identifier. * * @param identifier the algorithm's identifier */ public PermitUnlessDenyRuleAlg(URI identifier) { super(identifier); } @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); } }
3,906
33.883929
109
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/xacml3/DenyOverridesPolicyAlg.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.combine.xacml3; import org.wso2.balana.AbstractPolicy; import org.wso2.balana.MatchResult; import org.wso2.balana.ObligationResult; import org.wso2.balana.ctx.ResultFactory; import org.wso2.balana.combine.PolicyCombinerElement; import org.wso2.balana.combine.PolicyCombiningAlgorithm; import org.wso2.balana.ctx.AbstractResult; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.xacml3.Advice; import java.net.URI; import java.net.URISyntaxException; import java.util.*; /** * This is the new (XACML 3.0) the standard Deny Overrides policy combining algorithm. * It allows a single evaluation of Deny to take precedence over any number of permit, not applicable * or indeterminate results. Notethat since this implementation does an ordered evaluation, * this class also supports the Ordered Deny Overrides algorithm. */ public class DenyOverridesPolicyAlg extends PolicyCombiningAlgorithm { /** * The standard URN used to identify this algorithm */ public static final String algId = "urn:oasis:names:tc:xacml:3.0:policy-combining-algorithm:" + "deny-overrides"; // a URI form of the identifier private static URI identifierURI; // exception if the URI was invalid, which should never be a problem private static RuntimeException earlyException; static { try { identifierURI = new URI(algId); } catch (URISyntaxException se) { earlyException = new IllegalArgumentException(); earlyException.initCause(se); } } /** * Standard constructor. */ public DenyOverridesPolicyAlg() { super(identifierURI); if (earlyException != null){ throw earlyException; } } /** * Protected constructor used by the ordered version of this algorithm. * * @param identifier the algorithm's identifier */ protected DenyOverridesPolicyAlg(URI identifier) { super(identifier); } /** * 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 atLeastOneErrorD = false; boolean atLeastOneErrorP = false; boolean atLeastOneErrorDP = false; boolean atLeastOnePermit = false; AbstractResult firstIndeterminateResultD = null; AbstractResult firstIndeterminateResultP = null; AbstractResult firstIndeterminateResultDP = null; 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?ve need to check match if... return ResultFactory.getFactory().getResult(AbstractResult.DECISION_DENY, context); } if (match.getResult() == MatchResult.MATCH) { // evaluate the policy 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; } 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; } } else if(value == AbstractResult.DECISION_INDETERMINATE_DENY_OR_PERMIT){ atLeastOneErrorDP = true; // there are no rules about what to do if multiple cases // cause errors, so we'll just return the first one if(firstIndeterminateResultDP == null){ firstIndeterminateResultDP = result; } } } } } if(atLeastOneErrorDP){ return firstIndeterminateResultDP; } if (atLeastOneErrorD && (atLeastOneErrorP && atLeastOnePermit)){ return ResultFactory.getFactory().getResult(AbstractResult.DECISION_INDETERMINATE_DENY_OR_PERMIT, firstIndeterminateResultD.getStatus(), context); } if(atLeastOneErrorD){ return firstIndeterminateResultD; } if (atLeastOnePermit) { return ResultFactory.getFactory().getResult(AbstractResult.DECISION_PERMIT, permitObligations, permitAdvices, context); } if (atLeastOneErrorP){ return firstIndeterminateResultP; } // 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); } }
7,670
38.338462
124
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/xacml2/OrderedPermitOverridesRuleAlg.java
/* * @(#)OrderedPermitOverridesRuleAlg.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.combine.xacml2; import java.net.URI; import java.net.URISyntaxException; /** * This is the standard Ordered Permit Overrides rule combining algorithm. It allows a single * evaluation of Permit to take precedence over any number of deny, not applicable or indeterminate * results. Note that this uses the regular Permit Overrides implementation since it is also orderd. * * @since 1.1 * @author seth proctor */ public class OrderedPermitOverridesRuleAlg extends PermitOverridesRuleAlg { /** * The standard URN used to identify this algorithm */ public static final String algId = "urn:oasis:names:tc:xacml:1.1:rule-combining-algorithm:" + "ordered-permit-overrides"; // a URI form of the identifier private static URI identifierURI; // exception if the URI was invalid, which should never be a problem private static RuntimeException earlyException; static { try { identifierURI = new URI(algId); } catch (URISyntaxException se) { earlyException = new IllegalArgumentException(); earlyException.initCause(se); } } /** * Standard constructor. */ public OrderedPermitOverridesRuleAlg() { super(identifierURI); if (earlyException != null) throw earlyException; } }
3,202
38.060976
100
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/xacml2/FirstApplicablePolicyAlg.java
/* * @(#)FirstApplicablePolicyAlg.java * * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.combine.xacml2; import org.wso2.balana.AbstractPolicy; import org.wso2.balana.combine.PolicyCombinerElement; import org.wso2.balana.combine.PolicyCombiningAlgorithm; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.MatchResult; import org.wso2.balana.ctx.ResultFactory; import org.wso2.balana.ctx.AbstractResult; import org.wso2.balana.ctx.xacml2.Result; import java.net.URI; import java.net.URISyntaxException; import java.util.Iterator; import java.util.List; /** * This is the standard First Applicable policy combining algorithm. It looks through the set of * policies, finds the first one that applies, and returns that evaluation result. * * @since 1.0 * @author Seth Proctor */ public class FirstApplicablePolicyAlg extends PolicyCombiningAlgorithm { /** * The standard URN used to identify this algorithm */ public static final String algId = "urn:oasis:names:tc:xacml:1.0:policy-combining-algorithm:" + "first-applicable"; // a URI form of the identifier private static URI identifierURI; // exception if the URI was invalid, which should never be a problem private static RuntimeException earlyException; static { try { identifierURI = new URI(algId); } catch (URISyntaxException se) { earlyException = new IllegalArgumentException(); earlyException.initCause(se); } } /** * Standard constructor. */ public FirstApplicablePolicyAlg() { super(identifierURI); if (earlyException != null) throw earlyException; } /** * 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); } }
5,229
38.621212
101
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/xacml2/PermitOverridesPolicyAlg.java
/* * @(#)PermitOverridesPolicyAlg.java * * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.combine.xacml2; import org.wso2.balana.*; import org.wso2.balana.combine.PolicyCombinerElement; import org.wso2.balana.combine.PolicyCombiningAlgorithm; import org.wso2.balana.ctx.AbstractResult; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.ctx.ResultFactory; import org.wso2.balana.ctx.xacml2.Result; import org.wso2.balana.ctx.Status; import org.wso2.balana.xacml3.Advice; import java.net.URI; import java.net.URISyntaxException; import java.util.*; /** * This is the standard Permit Overrides policy combining algorithm. It allows a single evaluation * of Permit to take precedence over any number of deny, not applicable or indeterminate results. * Note that since this implementation does an ordered evaluation, this class also supports the * Ordered Permit Overrides algorithm. * * @since 1.0 * @author Seth Proctor */ public class PermitOverridesPolicyAlg extends PolicyCombiningAlgorithm { /** * The standard URN used to identify this algorithm */ public static final String algId = "urn:oasis:names:tc:xacml:1.0:policy-combining-algorithm:" + "permit-overrides"; // a URI form of the identifier private static URI identifierURI; // exception if the URI was invalid, which should never be a problem private static RuntimeException earlyException; static { try { identifierURI = new URI(algId); } catch (URISyntaxException se) { earlyException = new IllegalArgumentException(); earlyException.initCause(se); } } /** * Standard constructor. */ public PermitOverridesPolicyAlg() { super(identifierURI); if (earlyException != null) throw earlyException; } /** * Protected constructor used by the ordered version of this algorithm. * * @param identifier the algorithm's identifier */ protected PermitOverridesPolicyAlg(URI identifier) { super(identifier); } /** * 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); } }
7,245
39.480447
98
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/xacml2/FirstApplicableRuleAlg.java
/* * @(#)FirstApplicableRuleAlg.java * * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.combine.xacml2; import org.wso2.balana.combine.RuleCombinerElement; import org.wso2.balana.combine.RuleCombiningAlgorithm; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.ctx.ResultFactory; import org.wso2.balana.Rule; import org.wso2.balana.ctx.AbstractResult; import org.wso2.balana.ctx.xacml2.Result; import java.net.URI; import java.net.URISyntaxException; import java.util.Iterator; import java.util.List; /** * This is the standard First Applicable rule combining algorithm. It looks through the set of * rules, finds the first one that applies, and returns that evaluation result. * * @since 1.0 * @author Seth Proctor */ public class FirstApplicableRuleAlg extends RuleCombiningAlgorithm { /** * The standard URN used to identify this algorithm */ public static final String algId = "urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:" + "first-applicable"; // a URI form of the identifier private static URI identifierURI; // exception if the URI was invalid, which should never be a problem private static RuntimeException earlyException; static { try { identifierURI = new URI(algId); } catch (URISyntaxException se) { earlyException = new IllegalArgumentException(); earlyException.initCause(se); } } /** * Standard constructor. */ public FirstApplicableRuleAlg() { super(identifierURI); if (earlyException != null) throw earlyException; } /** * 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); } }
4,622
36.893443
95
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/xacml2/OrderedDenyOverridesRuleAlg.java
/* * @(#)OrderedDenyOverridesRuleAlg.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.combine.xacml2; import org.wso2.balana.combine.xacml2.DenyOverridesRuleAlg; import java.net.URI; import java.net.URISyntaxException; /** * This is the standard Ordered Deny Overrides rule combining algorithm. It allows a single * evaluation of Deny to take precedence over any number of permit, not applicable or indeterminate * results. Note that this uses the regular Deny Overrides implementation since it is also orderd. * * @since 1.1 * @author seth proctor */ public class OrderedDenyOverridesRuleAlg extends DenyOverridesRuleAlg { /** * The standard URN used to identify this algorithm */ public static final String algId = "urn:oasis:names:tc:xacml:1.1:rule-combining-algorithm:" + "ordered-deny-overrides"; // a URI form of the identifier private static URI identifierURI; // exception if the URI was invalid, which should never be a problem private static RuntimeException earlyException; static { try { identifierURI = new URI(algId); } catch (URISyntaxException se) { earlyException = new IllegalArgumentException(); earlyException.initCause(se); } } /** * Standard constructor. */ public OrderedDenyOverridesRuleAlg() { super(identifierURI); if (earlyException != null) throw earlyException; } }
3,249
37.690476
99
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/xacml2/OrderedDenyOverridesPolicyAlg.java
/* * OrderedDenyOverridesPolicyAlg.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.combine.xacml2; import org.wso2.balana.combine.xacml2.DenyOverridesPolicyAlg; import java.net.URI; import java.net.URISyntaxException; /** * This is the standard Ordered Deny Overrides policy combining algorithm. It allows a single * evaluation of Deny to take precedence over any number of permit, not applicable or indeterminate * results. Note that this uses the regular Deny Overrides implementation since it is also orderd. * * @since 1.1 * @author seth proctor */ public class OrderedDenyOverridesPolicyAlg extends DenyOverridesPolicyAlg { /** * The standard URN used to identify this algorithm */ public static final String algId = "urn:oasis:names:tc:xacml:1.1:policy-combining-algorithm:" + "ordered-deny-overrides"; // a URI form of the identifier private static URI identifierURI; // exception if the URI was invalid, which should never be a problem private static RuntimeException earlyException; static { try { identifierURI = new URI(algId); } catch (URISyntaxException se) { earlyException = new IllegalArgumentException(); earlyException.initCause(se); } } /** * Standard constructor. */ public OrderedDenyOverridesPolicyAlg() { super(identifierURI); if (earlyException != null) throw earlyException; } }
3,259
37.809524
99
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/xacml2/OrderedPermitOverridesPolicyAlg.java
/* * @(#)OrderedPermitOverridesPolicyAlg.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.combine.xacml2; import java.net.URI; import java.net.URISyntaxException; /** * This is the standard Ordered Permit Overrides policy combining algorithm. It allows a single * evaluation of Permit to take precedence over any number of deny, not applicable or indeterminate * results. Note that this uses the regular Permit Overrides implementation since it is also orderd. * * @since 1.1 * @author seth proctor */ public class OrderedPermitOverridesPolicyAlg extends PermitOverridesPolicyAlg { /** * The standard URN used to identify this algorithm */ public static final String algId = "urn:oasis:names:tc:xacml:1.1:policy-combining-algorithm:" + "ordered-permit-overrides"; // a URI form of the identifier private static URI identifierURI; // exception if the URI was invalid, which should never be a problem private static RuntimeException earlyException; static { try { identifierURI = new URI(algId); } catch (URISyntaxException se) { earlyException = new IllegalArgumentException(); earlyException.initCause(se); } } /** * Standard constructor. */ public OrderedPermitOverridesPolicyAlg() { super(identifierURI); if (earlyException != null) throw earlyException; } }
3,214
38.207317
100
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/xacml2/DenyOverridesRuleAlg.java
/* * @(#)DenyOverridesRuleAlg.java * * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.combine.xacml2; import org.wso2.balana.combine.RuleCombinerElement; import org.wso2.balana.combine.RuleCombiningAlgorithm; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.ObligationResult; import org.wso2.balana.ctx.ResultFactory; import org.wso2.balana.Rule; import org.wso2.balana.ctx.AbstractResult; import org.wso2.balana.xacml3.Advice; import java.net.URI; import java.net.URISyntaxException; import java.util.*; /** * This is the standard Deny Overrides rule combining algorithm. It allows a single evaluation of * Deny to take precedence over any number of permit, not applicable or indeterminate results. Note * that since this implementation does an ordered evaluation, this class also supports the Ordered * Deny Overrides algorithm. * * @since 1.0 * @author Seth Proctor */ public class DenyOverridesRuleAlg extends RuleCombiningAlgorithm { /** * The standard URN used to identify this algorithm */ public static final String algId = "urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:" + "deny-overrides"; // a URI form of the identifier private static URI identifierURI; // exception if the URI was invalid, which should never be a problem private static RuntimeException earlyException; static { try { identifierURI = new URI(algId); } catch (URISyntaxException se) { earlyException = new IllegalArgumentException(); earlyException.initCause(se); } } /** * Standard constructor. */ public DenyOverridesRuleAlg() { super(identifierURI); if (earlyException != null) throw earlyException; } /** * Protected constructor used by the ordered version of this algorithm. * * @param identifier the algorithm's identifier */ protected DenyOverridesRuleAlg(URI identifier) { super(identifier); } /** * 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); } }
7,742
39.752632
111
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/xacml2/PermitOverridesRuleAlg.java
/* * @(#)PermitOverridesRuleAlg.java * * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.combine.xacml2; import org.wso2.balana.combine.RuleCombinerElement; import org.wso2.balana.combine.RuleCombiningAlgorithm; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.ObligationResult; import org.wso2.balana.ctx.ResultFactory; import org.wso2.balana.Rule; import org.wso2.balana.ctx.AbstractResult; import org.wso2.balana.xacml3.Advice; import java.net.URI; import java.net.URISyntaxException; import java.util.*; /** * This is the standard Permit Overrides rule combining algorithm. It allows a single evaluation of * Permit to take precedence over any number of deny, not applicable or indeterminate results. Note * that since this implementation does an ordered evaluation, this class also supports the Ordered * Permit Overrides algorithm. * * @since 1.0 * @author Seth Proctor */ public class PermitOverridesRuleAlg extends RuleCombiningAlgorithm { /** * The standard URN used to identify this algorithm */ public static final String algId = "urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:" + "permit-overrides"; // a URI form of the identifier private static URI identifierURI; // exception if the URI was invalid, which should never be a problem private static RuntimeException earlyException; static { try { identifierURI = new URI(algId); } catch (URISyntaxException se) { earlyException = new IllegalArgumentException(); earlyException.initCause(se); } } /** * Standard constructor. */ public PermitOverridesRuleAlg() { super(identifierURI); if (earlyException != null) throw earlyException; } /** * Protected constructor used by the ordered version of this algorithm. * * @param identifier the algorithm's identifier */ protected PermitOverridesRuleAlg(URI identifier) { super(identifier); } /** * 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); } }
7,605
40.336957
102
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/xacml2/OnlyOneApplicablePolicyAlg.java
/* * @(#)OnlyOneApplicablePolicyAlg.java * * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.combine.xacml2; import org.wso2.balana.AbstractPolicy; import org.wso2.balana.combine.PolicyCombinerElement; import org.wso2.balana.combine.PolicyCombiningAlgorithm; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.MatchResult; import org.wso2.balana.ctx.ResultFactory; import org.wso2.balana.ctx.AbstractResult; import org.wso2.balana.ctx.Status; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * This is the standard Only One Applicable Policy combining algorithm. This is a special algorithm * used at the root of a policy/pdp to make sure that pdp only selects one policy per request. * * @since 1.0 * @author Seth Proctor */ public class OnlyOneApplicablePolicyAlg extends PolicyCombiningAlgorithm { /** * The standard URN used to identify this algorithm */ public static final String algId = "urn:oasis:names:tc:xacml:1.0:policy-combining-algorithm:" + "only-one-applicable"; // a URI form of the identifier private static URI identifierURI; // exception if the URI was invalid, which should never be a problem private static RuntimeException earlyException; static { try { identifierURI = new URI(algId); } catch (URISyntaxException se) { earlyException = new IllegalArgumentException(); earlyException.initCause(se); } } /** * Standard constructor. */ public OnlyOneApplicablePolicyAlg() { super(identifierURI); if (earlyException != null) throw earlyException; } /** * 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); } }
5,987
38.92
101
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/combine/xacml2/DenyOverridesPolicyAlg.java
/* * @(#)DenyOverridesPolicyAlg.java * * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.combine.xacml2; import org.wso2.balana.*; import org.wso2.balana.combine.PolicyCombinerElement; import org.wso2.balana.combine.PolicyCombiningAlgorithm; import org.wso2.balana.ctx.AbstractResult; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.ctx.ResultFactory; import org.wso2.balana.ctx.xacml2.Result; import org.wso2.balana.xacml3.Advice; import java.net.URI; import java.net.URISyntaxException; import java.util.*; /** * This is the standard Deny Overrides policy combining algorithm. It allows a single evaluation of * Deny to take precedence over any number of permit, not applicable or indeterminate results. Note * that since this implementation does an ordered evaluation, this class also supports the Ordered * Deny Overrides algorithm. * * @since 1.0 * @author Seth Proctor */ public class DenyOverridesPolicyAlg extends PolicyCombiningAlgorithm { /** * The standard URN used to identify this algorithm */ public static final String algId = "urn:oasis:names:tc:xacml:1.0:policy-combining-algorithm:" + "deny-overrides"; // a URI form of the identifier private static URI identifierURI; // exception if the URI was invalid, which should never be a problem private static RuntimeException earlyException; static { try { identifierURI = new URI(algId); } catch (URISyntaxException se) { earlyException = new IllegalArgumentException(); earlyException.initCause(se); } } /** * Standard constructor. */ public DenyOverridesPolicyAlg() { super(identifierURI); if (earlyException != null) throw earlyException; } /** * Protected constructor used by the ordered version of this algorithm. * * @param identifier the algorithm's identifier */ protected DenyOverridesPolicyAlg(URI identifier) { super(identifier); } /** * 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); } } }
6,728
39.781818
106
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/ctx/StatusDetail.java
/* * @(#)StatusDetail.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.ctx; import org.wso2.balana.Balana; import org.wso2.balana.DOMHelper; import org.wso2.balana.ParsingException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringWriter; import java.util.List; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.wso2.balana.utils.Utils; import org.xml.sax.SAXException; /** * This class represents the StatusDetailType in the context schema. Because status detail is * defined as a sequence of xs:any XML type, the data in this class must be generic, and it is up to * the application developer to interpret the data appropriately. * * @since 1.0 * @author Seth Proctor */ public class StatusDetail { // the text version, if it's avilable already private String detailText = null; /** * a List of MissingAttributeDetail */ private List<MissingAttributeDetail> missingAttributeDetails; /** * Constructor that uses a <code>List</code> of <code>MissingAttributeDetail</code>s to define the status * detail. This is a common form of detail data, and can be used for things like providing the * information included with the missing-attribute status code. * * @param missingAttributeDetails a <code>List</code> of <code>MissingAttributeDetail</code>s * * @throws IllegalArgumentException if there is a problem encoding the <code>MissingAttributeDetail</code>s */ public StatusDetail(List<MissingAttributeDetail> missingAttributeDetails) throws IllegalArgumentException { this.missingAttributeDetails = missingAttributeDetails; try { detailText = "<StatusDetail>\n"; for (MissingAttributeDetail attribute : missingAttributeDetails) { detailText += attribute.getEncoded() + "\n"; } detailText += "</StatusDetail>"; } catch (ParsingException pe) { // really, this should never happen, since we just made sure that // we're working with valid text, but it's possible that encoding // the attribute could have caused problems... throw new IllegalArgumentException("Invalid MissingAttributeDetail data, caused by " + pe.getMessage()); } } /** * Constructor that takes the text-encoded form of the XML to use as the status data. The * encoded text will be wrapped with the <code>StatusDetail</code> XML tag, and the resulting * text must be valid XML or a <code>ParsingException</code> will be thrown. * * @param encoded a non-null <code>String</code> that encodes the status detail * * @throws ParsingException if the encoded text is invalid XML */ public StatusDetail(String encoded) throws ParsingException { detailText = "<StatusDetail>\n" + encoded + "\n</StatusDetail>"; } /** * Private constructor that just sets the root node. This interface is provided publically * through the getInstance method. * * @param root the DOM root of StatusDetail element */ private StatusDetail(Node root) { try{ detailText = nodeToText(root); } catch (ParsingException e) { // just ignore as this is not a must to convert this to text } } /** * Private helper routine that converts text into a node * * @param encoded * @return * @throws ParsingException */ private Node textToNode(String encoded) throws ParsingException { try { String text = "<?xml version=\"1.0\"?>\n"; byte[] bytes = (text + encoded).getBytes(); DocumentBuilderFactory documentBuilderFactory = Utils.getSecuredDocumentBuilderFactory(); DocumentBuilder db = documentBuilderFactory.newDocumentBuilder(); Document doc = db.parse(new ByteArrayInputStream(bytes)); return doc.getDocumentElement(); } catch (ParserConfigurationException | SAXException | IOException e) { throw new ParsingException("invalid XML for status detail", e); } } /** * Private helper routine that converts text into a node * * @param node * @return * @throws ParsingException */ private String nodeToText(Node node) throws ParsingException { StringWriter sw = new StringWriter(); try { TransformerFactory factory = TransformerFactory.newInstance(); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(new DOMSource(node), new StreamResult(sw)); } catch (TransformerException te) { throw new ParsingException("invalid XML for status detail"); } return sw.toString(); } /** * Creates an instance of a <code>StatusDetail</code> object based on the given DOM root node. * The node must be a valid StatusDetailType root, or else a <code>ParsingException</code> is * thrown. * * @param root the DOM root of the StatusDetailType XML type * * @return a new <code>StatusDetail</code> object * * @throws ParsingException if the root node is invalid */ public static StatusDetail getInstance(Node root) throws ParsingException { // check that it's really a StatusDetailType root if (!DOMHelper.getLocalName(root).equals("StatusDetail")){ throw new ParsingException("not a StatusDetail node"); } return new StatusDetail(root); } /** * Gets List of <code>MissingAttributeDetail</code> elements * * @return a <code>List</code> of <code>MissingAttributeDetail</code> */ public List<MissingAttributeDetail> getMissingAttributeDetails() { return missingAttributeDetails; } /** * Returns the text-encoded version of this data, if possible. If the <code>String</code> form * constructor was used, this will just be the original text wrapped with the StatusData tag. If * the <code>List</code> form constructor was used, it will be the encoded attribute data. If * this was created using the <code>getInstance</code> method, then <code>getEncoded</code> will * throw an exception. * * @return the encoded form of this data * * @throws IllegalStateException if this object was created using the <code>getInstance</code> * method */ public String getEncoded() throws IllegalStateException { if (detailText == null){ throw new IllegalStateException("no encoded form available"); } return detailText; } }
9,318
38.995708
111
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/ctx/ResourceActionMapping.java
package org.wso2.balana.ctx; public class ResourceActionMapping { private String resourceName; private String actionName; private String envName; public ResourceActionMapping() { } public ResourceActionMapping(String resourceName, String actionName, String envName) { super(); this.resourceName = resourceName; this.actionName = actionName; this.envName = envName; } public String getEnvName() { return envName; } public void setEnvName(String envName) { this.envName = envName; } public String getResourceName() { return resourceName; } public void setResourceName(String resourceName) { this.resourceName = resourceName; } public String getActionName() { return actionName; } public void setActionName(String actionName) { this.actionName = actionName; } }
927
19.622222
90
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/ctx/Status.java
/* * @(#)Status.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.ctx; import org.wso2.balana.DOMHelper; import org.wso2.balana.Indenter; import org.wso2.balana.ParsingException; import java.io.OutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Represents the status data that is included in a ResultType. By default, the status is OK. * * @since 1.0 * @author Seth Proctor */ public class Status { /** * Standard identifier for the OK status */ public static final String STATUS_OK = "urn:oasis:names:tc:xacml:1.0:status:ok"; /** * Standard identifier for the MissingAttribute status */ public static final String STATUS_MISSING_ATTRIBUTE = "urn:oasis:names:tc:xacml:1.0:status:missing-attribute"; /** * Standard identifier for the SyntaxError status */ public static final String STATUS_SYNTAX_ERROR = "urn:oasis:names:tc:xacml:1.0:status:syntax-error"; /** * Standard identifier for the ProcessingError status */ public static final String STATUS_PROCESSING_ERROR = "urn:oasis:names:tc:xacml:1.0:status:processing-error"; // the status code private List<String> code; // the message private String message; // the detail private StatusDetail detail; // a single OK object we'll use most of the time private static Status okStatus; // initialize the OK Status object static { List<String> code = new ArrayList<String>(); code.add(STATUS_OK); okStatus = new Status(code); }; /** * Constructor that takes only the status code. * * @param code a <code>List</code> of <code>String</code> codes, typically just one code, but * this may contain any number of minor codes after the first item in the list, which * is the major code */ public Status(List<String> code) { this(code, null, null); } /** * Constructor that takes both the status code and a message to include with the status. * * @param code a <code>List</code> of <code>String</code> codes, typically just one code, but * this may contain any number of minor codes after the first item in the list, which * is the major code * @param message a message to include with the code */ public Status(List<String> code, String message) { this(code, message, null); } /** * Constructor that takes the status code, an optional message, and some detail to include with * the status. Note that the specification explicitly says that a status code of OK, SyntaxError * or ProcessingError may not appear with status detail, so an exception is thrown if one of * these status codes is used and detail is included. * * @param code a <code>List</code> of <code>String</code> codes, typically just one code, but * this may contain any number of minor codes after the first item in the list, which * is the major code * @param message a message to include with the code, or null if there should be no message * @param detail the status detail to include, or null if there is no detail * * @throws IllegalArgumentException if detail is included for a status code that doesn't allow * detail */ public Status(List<String> code, String message, StatusDetail detail) throws IllegalArgumentException { // if the code is ok, syntax error or processing error, there // must not be any detail included if (detail != null) { String c = (String) (code.iterator().next()); if (c.equals(STATUS_OK) || c.equals(STATUS_SYNTAX_ERROR) || c.equals(STATUS_PROCESSING_ERROR)) throw new IllegalArgumentException("status detail cannot be " + "included with " + c); } this.code = Collections.unmodifiableList(new ArrayList<String>(code)); this.message = message; this.detail = detail; } /** * Returns the status code. * * @return the status code */ public List<String> getCode() { return code; } /** * Returns the status message or null if there is none. * * @return the status message or null */ public String getMessage() { return message; } /** * Returns the status detail or null if there is none. * * @return a <code>StatusDetail</code> or null */ public StatusDetail getDetail() { return detail; } /** * Gets a <code>Status</code> instance that has the OK status and no other information. This is * the default status data for all responses except Indeterminate ones. * * @return an instance with <code>STATUS_OK</code> */ public static Status getOkInstance() { return okStatus; } /** * Creates a new instance of <code>Status</code> based on the given DOM root node. A * <code>ParsingException</code> is thrown if the DOM root doesn't represent a valid StatusType. * * @param root the DOM root of a StatusType * * @return a new <code>Status</code> * * @throws ParsingException if the node is invalid */ public static Status getInstance(Node root) throws ParsingException { List<String> code = null; String message = null; StatusDetail detail = 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("StatusCode")) { code = parseStatusCode(node); } else if (name.equals("StatusMessage")) { message = node.getFirstChild().getNodeValue(); } else if (name.equals("StatusDetail")) { detail = StatusDetail.getInstance(node); } } if(code == null){ throw new ParsingException("Missing required element StatusCode in StatusType"); } return new Status(code, message, detail); } /** * Private helper that parses the status code * * @param root the DOM root of a StatusCodeType * * @return a List for status */ private static List<String> parseStatusCode(Node root) { // get the top-level code String val = root.getAttributes().getNamedItem("Value").getNodeValue(); List<String> code = new ArrayList<String>(); code.add(val); // now get the list of all sub-codes, and work through them NodeList list = ((Element) root).getElementsByTagName("StatusCode"); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); code.add(node.getAttributes().getNamedItem("Value").getNodeValue()); } return code; } /** * Encodes this <code>Status</code> into its XML form * * @return <code>String</code> */ public String encode() { StringBuilder builder = new StringBuilder(); encode(builder); return builder.toString(); } /** * Encodes this <code>Status</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("<Status>"); encodeStatusCode(code.iterator(), builder); if (message != null){ builder.append("<StatusMessage>").append(message).append("</StatusMessage>"); } if (detail != null) { builder.append(detail.getEncoded()); } builder.append("</Status>"); } /** * Encodes the object in XML * * @param iterator * @param builder */ private void encodeStatusCode(Iterator<String> iterator, StringBuilder builder) { String code = iterator.next(); if (iterator.hasNext()) { builder.append("<StatusCode Value=\"").append(code).append("\">"); encodeStatusCode(iterator, builder); builder.append("</StatusCode>"); } else { builder.append("<StatusCode Value=\"").append(code).append("\"/>"); } } }
10,438
33.22623
117
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/ctx/BasicEvaluationCtx.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.ctx; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Node; import org.wso2.balana.PDPConfig; import org.wso2.balana.attr.BagAttribute; import org.wso2.balana.attr.DateAttribute; import org.wso2.balana.attr.DateTimeAttribute; import org.wso2.balana.attr.TimeAttribute; import org.wso2.balana.cond.EvaluationResult; import java.net.URI; import java.util.Date; /** * Implementation of <code>EvaluationCtx</code>. This implements some generic methods that * commons to most of the implementations */ public abstract class BasicEvaluationCtx implements EvaluationCtx { /** * the cached current date, time, and date time, * which we may or may not be using depending on how this object was constructed */ protected DateAttribute currentDate; protected TimeAttribute currentTime; protected DateTimeAttribute currentDateTime; /** * TODO what is this? */ protected boolean useCachedEnvValues = false; /** * the DOM root the original RequestContext document */ protected Node requestRoot; /** * PDP configurations */ protected PDPConfig pdpConfig; /** * logger */ private static final Log logger = LogFactory.getLog(BasicEvaluationCtx.class); /** * Returns the DOM root of the original RequestType XML document. * * @return the DOM root node */ public Node getRequestRoot() { return requestRoot; } /** * TODO * @return */ public boolean isSearching() { return false; } /** * Returns the value for the current time. The current time, current date, and current dateTime * are consistent, so that they all represent the same moment. If this is the first time that * one of these three values has been requested, and caching is enabled, then the three values * will be resolved and stored. * <p/> * Note that the value supplied here applies only to dynamically resolved values, not those * supplied in the Request. In other words, this always returns a dynamically resolved value * local to the PDP, even if a different value was supplied in the Request. This is handled * correctly when the value is requested by its identifier. * * @return the current time */ public synchronized TimeAttribute getCurrentTime() { long millis = dateTimeHelper(); if (useCachedEnvValues) return currentTime; else return new TimeAttribute(new Date(millis)); } /** * Returns the value for the current date. The current time, current date, and current dateTime * are consistent, so that they all represent the same moment. If this is the first time that * one of these three values has been requested, and caching is enabled, then the three values * will be resolved and stored. * <p/> * Note that the value supplied here applies only to dynamically resolved values, not those * supplied in the Request. In other words, this always returns a dynamically resolved value * local to the PDP, even if a different value was supplied in the Request. This is handled * correctly when the value is requested by its identifier. * * @return the current date */ public synchronized DateAttribute getCurrentDate() { long millis = dateTimeHelper(); if (useCachedEnvValues) return currentDate; else return new DateAttribute(new Date(millis)); } /** * Returns the value for the current dateTime. The current time, current date, and current * dateTime are consistent, so that they all represent the same moment. If this is the first * time that one of these three values has been requested, and caching is enabled, then the * three values will be resolved and stored. * <p/> * Note that the value supplied here applies only to dynamically resolved values, not those * supplied in the Request. In other words, this always returns a dynamically resolved value * local to the PDP, even if a different value was supplied in the Request. This is handled * correctly when the value is requested by its identifier. * * @return the current dateTime */ public synchronized DateTimeAttribute getCurrentDateTime() { long millis = dateTimeHelper(); if (useCachedEnvValues) return currentDateTime; else return new DateTimeAttribute(new Date(millis)); } public abstract AbstractRequestCtx getRequestCtx(); /** * 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)); } } /** * Private helper that figures out if we need to resolve new values, and returns either the * current moment (if we're not caching) or -1 (if we are caching) * * @return current moment as long value */ private long dateTimeHelper() { // if we already have current values, then we can stop (note this // always means that we're caching) if (currentTime != null) return -1; // get the current moment Date time = new Date(); long millis = time.getTime(); // if we're not caching then we just return the current moment if (!useCachedEnvValues) { return millis; } else { // we're caching, so resolve all three values, making sure // to use clean copies of the date object since it may be // modified when creating the attributes currentTime = new TimeAttribute(time); currentDate = new DateAttribute(new Date(millis)); currentDateTime = new DateTimeAttribute(new Date(millis)); } return -1; } /** * 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)); } } }
8,869
36.112971
99
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/ctx/AttributeAssignment.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.ctx; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.wso2.balana.DOMHelper; import org.wso2.balana.Indenter; import org.wso2.balana.ParsingException; import org.wso2.balana.attr.AttributeFactory; import org.wso2.balana.attr.AttributeValue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.io.PrintStream; import java.net.URI; /** * Represents AttributeAssignmentType in the XACML 3.0 and 2.0 policy schema * This is used for including arguments in obligations and advices */ public class AttributeAssignment extends AttributeValue { /** * attribute id of the AttributeAssignment element */ private URI attributeId; /** * category of the AttributeAssignment element whether it is subject, action and etc */ private URI category; /** * issuer of the AttributeAssignment */ private String issuer; /** * content as String */ private String content; /** * Constructor that creates a new <code>AttributeAssignment</code> based on the given elements. * @param attributeId attribute id of the AttributeAssignment element * @param dataType attributes datatype * @param category category of the AttributeAssignment element whether it is subject, action and etc * @param content Content as String * @param issuer issuer of the AttributeAssignment */ public AttributeAssignment(URI attributeId, URI dataType, URI category, String content, String issuer) { super(dataType); this.attributeId = attributeId; this.category = category; this.issuer = issuer; this.content = content; } /** * TODO remove this method if possible * creates a <code>AttributeAssignment</code> based on its DOM node. * * @param root root the node to parse for the AttributeAssignment * @return a new <code>AttributeAssignment</code> constructed by parsing * @throws ParsingException if the DOM node is invalid */ public static AttributeAssignment getInstance(Node root) throws ParsingException { URI attributeId; URI category = null; URI type; String issuer = null; String content = null; if (!DOMHelper.getLocalName(root).equals("AttributeAssignment")) { throw new ParsingException("AttributeAssignment object cannot be created " + "with root node of type: " + DOMHelper.getLocalName(root)); } NamedNodeMap nodeAttributes = root.getAttributes(); try { attributeId = new URI(nodeAttributes.getNamedItem("AttributeId").getNodeValue()); } catch (Exception e) { throw new ParsingException("Error parsing required AttributeId in " + "AttributeAssignmentType", e); } try { type = new URI(nodeAttributes.getNamedItem("DataType").getNodeValue()); } catch (Exception e) { throw new ParsingException("Error parsing required AttributeId in " + "AttributeAssignmentType", e); } try { Node categoryNode = nodeAttributes.getNamedItem("Category"); if(categoryNode != null){ category = new URI(categoryNode.getNodeValue()); } Node issuerNode = nodeAttributes.getNamedItem("Issuer"); if(issuerNode != null){ issuer = issuerNode.getNodeValue(); } content = root.getTextContent(); } catch (Exception e) { throw new ParsingException("Error parsing optional attributes in " + "AttributeAssignmentType", e); } return new AttributeAssignment(attributeId, type, category, content, issuer); } public URI getAttributeId() { return attributeId; } public URI getCategory() { return category; } public String getIssuer() { return issuer; } public String getContent() { return content; } /** * Encodes this <code>AttributeAssignment</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("<AttributeAssignment AttributeId=\"").append(attributeId).append("\""); builder.append(" DataType=\"").append(getType()).append("\""); if(category != null){ builder.append(" Category=\"").append(category).append("\""); } if(issuer != null){ builder.append("\" Issuer=\"").append(issuer).append("\""); } builder.append(">"); if(content != null){ builder.append(content); } builder.append("</AttributeAssignment>\n"); } @Override /** * Encodes this <code>AttributeAssignment</code> into its XML form * * @return <code>String</code> */ public String encode() { StringBuilder builder = new StringBuilder(); encode(builder); return builder.toString(); } }
6,033
30.427083
106
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/ctx/AbstractRequestCtx.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.ctx; import org.w3c.dom.Node; import org.wso2.balana.Indenter; import org.wso2.balana.xacml3.Attributes; import java.io.OutputStream; import java.util.Set; /** * Represents a XACML request made to the PDP. This is the class that contains all the data used to start * a policy evaluation.abstract class has been defined to give a unique interface for both XACML 2.0 * and XACML 3.0 RequestCtx */ public abstract class AbstractRequestCtx { //XACML version of the request protected int xacmlVersion; // Hold onto the root of the document for XPath searches protected Node documentRoot = null; /** * XACML3 attributes as <code>Attributes</code> objects */ protected Set<Attributes> attributesSet = null; protected boolean isSearch; /** * Returns the root DOM node of the document used to create this object, or null if this object * was created by hand (ie, not through the <code>getInstance</code> method) or if the root node * was not provided to the constructor. * * @return the root DOM node or null */ public Node getDocumentRoot() { return documentRoot; } public void setSearch(boolean isSearch) { this.isSearch = isSearch; } public boolean isSearch() { return isSearch; } public int getXacmlVersion() { return xacmlVersion; } public void setXacmlVersion(int xacmlVersion) { this.xacmlVersion = xacmlVersion; } /** * Returns a <code>Set</code> containing <code>Attribute</code> objects. * * @return the request' s all attributes as <code>Set</code> */ public Set<Attributes> getAttributesSet() { return attributesSet; } /** * Encodes this <code>AbstractRequestCtx</code> into its XML representation and writes this encoding to the given * <code>OutputStream</code> with indentation. * * @param output a stream into which the XML-encoded data is written * @param indenter an object that creates indentation strings */ public abstract void encode(OutputStream output, Indenter indenter); /** * Encodes this <code>AbstractRequestCtx</code> into its XML representation and writes this encoding to the given * <code>OutputStream</code>. No indentation is used. * * @param output a stream into which the XML-encoded data is written */ public abstract void encode(OutputStream output); }
3,159
29.980392
118
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/ctx/RequestCtxFactory.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.ctx; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.wso2.balana.Balana; import org.wso2.balana.ParsingException; import org.wso2.balana.XACMLConstants; import org.wso2.balana.ctx.xacml3.RequestCtx; import org.wso2.balana.utils.Utils; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; /** * Factory that creates the AbstractRequestCtx */ public class RequestCtxFactory { /** * Instance of this class */ private static volatile RequestCtxFactory factoryInstance; /** * the logger we'll use for all messages */ private static final Log log = LogFactory.getLog(RequestCtxFactory.class); /** * Returns instance of <code>AbstractRequestCtx</code> based one the XACML version. * * @param root the node to parse for the <code>AbstractRequestCtx</code> * @return <code>AbstractRequestCtx</code> object * @throws org.wso2.balana.ParsingException if the DOM node is invalid */ public AbstractRequestCtx getRequestCtx(Node root) throws ParsingException { String requestCtxNs = root.getNamespaceURI(); if(requestCtxNs != null){ if(XACMLConstants.REQUEST_CONTEXT_3_0_IDENTIFIER.equals(requestCtxNs.trim())){ return RequestCtx.getInstance(root); } else if(XACMLConstants.REQUEST_CONTEXT_1_0_IDENTIFIER.equals(requestCtxNs.trim()) || XACMLConstants.REQUEST_CONTEXT_2_0_IDENTIFIER.equals(requestCtxNs.trim())) { return org.wso2.balana.ctx.xacml2.RequestCtx.getInstance(root); } else { throw new ParsingException("Invalid namespace in XACML request"); } } else { log.warn("No Namespace defined in XACML request and Assume as XACML 3.0"); return RequestCtx.getInstance(root); } } /** * Returns instance of <code>AbstractRequestCtx</code> based one the XACML version. * * @param request the String to parse for the <code>AbstractRequestCtx</code> * @return <code>AbstractRequestCtx</code> object * @throws ParsingException if the request is invalid */ public AbstractRequestCtx getRequestCtx(String request) throws ParsingException { Node root = getXacmlRequest(request); String requestCtxNs = root.getNamespaceURI(); if(requestCtxNs != null){ if(XACMLConstants.REQUEST_CONTEXT_3_0_IDENTIFIER.equals(requestCtxNs.trim())){ return RequestCtx.getInstance(root); } else if(XACMLConstants.REQUEST_CONTEXT_1_0_IDENTIFIER.equals(requestCtxNs.trim()) || XACMLConstants.REQUEST_CONTEXT_2_0_IDENTIFIER.equals(requestCtxNs.trim())) { return org.wso2.balana.ctx.xacml2.RequestCtx.getInstance(root); } else { throw new ParsingException("Invalid namespace in XACML request"); } } else { log.warn("No Namespace defined in XACML request and Assume as XACML 3.0"); return RequestCtx.getInstance(root); } } /** * Returns instance of <code>AbstractRequestCtx</code> based one the XACML version. * * Creates a new <code>RequestCtx</code> by parsing XML from an input stream. Note that this a * convenience method, and it will not do schema validation by default. You should be parsing * the data yourself, and then providing the root node to the other <code>getInstance</code> * method. If you use this convenience method, you probably want to turn on validation by * setting the context schema file (see the programmer guide for more information on this). * * @param input input a stream providing the XML data * @return <code>AbstractRequestCtx</code> object * @throws ParsingException if the DOM node is invalid */ public AbstractRequestCtx getRequestCtx(InputStream input) throws ParsingException { Node root = InputParser.parseInput(input, "Request"); String requestCtxNs = root.getNamespaceURI(); if(requestCtxNs != null){ if(XACMLConstants.REQUEST_CONTEXT_3_0_IDENTIFIER.equals(requestCtxNs.trim())){ return RequestCtx.getInstance(root); } else if(XACMLConstants.REQUEST_CONTEXT_1_0_IDENTIFIER.equals(requestCtxNs.trim()) || XACMLConstants.REQUEST_CONTEXT_2_0_IDENTIFIER.equals(requestCtxNs.trim())) { return org.wso2.balana.ctx.xacml2.RequestCtx.getInstance(root); } else { throw new ParsingException("Invalid namespace in XACML request"); } } else { log.warn("No Namespace defined in XACML request and Assume as XACML 3.0"); return RequestCtx.getInstance(root); } } /** * Returns an instance of this factory. This method enforces a singleton model, meaning that * this always returns the same instance, creating the factory if it hasn't been requested * before. * * @return the factory instance */ public static RequestCtxFactory getFactory() { if (factoryInstance == null) { synchronized (RequestCtxFactory.class) { if (factoryInstance == null) { factoryInstance = new RequestCtxFactory(); } } } return factoryInstance; } /** * Creates DOM representation of the XACML request * * @param request XACML request as a String object * @return XACML request as a DOM element * @throws ParsingException throws, if fails */ public Element getXacmlRequest(String request) throws ParsingException { ByteArrayInputStream inputStream = new ByteArrayInputStream(request.getBytes()); DocumentBuilderFactory builder = Utils.getSecuredDocumentBuilderFactory(); if(builder == null){ throw new ParsingException("DOM Builder can not be null"); } Document doc; try { doc = builder.newDocumentBuilder().parse(inputStream); } catch (Exception e) { throw new ParsingException("DOM of request element can not be created from String", e); } finally { try { inputStream.close(); } catch (IOException e) { log.error("Error in closing input stream of XACML request"); } } return doc.getDocumentElement(); } }
7,433
37.71875
99
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/ctx/AbstractResult.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.ctx; import org.wso2.balana.*; import org.wso2.balana.xacml3.Advice; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; /** * Abstract Represents the ResultType XML object from the Context schema. Any number * of these may included in a <code>ResponseCtx</code>. This class provides an abstract method to * encode XACML result with the decision effect, as well as an optional status data and obligations * and advices. encode method must be implemented under the concert class. * */ public abstract class AbstractResult { /** * The decision to permit the request */ public static final int DECISION_PERMIT = 0; /** * The decision to deny the request */ public static final int DECISION_DENY = 1; /** * The decision that a decision about the request cannot be made */ public static final int DECISION_INDETERMINATE = 2; /** * The decision that nothing applied to us */ public static final int DECISION_NOT_APPLICABLE = 3; /** * The decision that a decision about the request cannot be made */ public static final int DECISION_INDETERMINATE_DENY = 4; /** * The decision that a decision about the request cannot be made */ public static final int DECISION_INDETERMINATE_PERMIT = 5; /** * The decision that a decision about the request cannot be made */ public static final int DECISION_INDETERMINATE_DENY_OR_PERMIT = 6; /** * string versions of the 4 Decision types used for encoding */ public static final String[] DECISIONS = { "Permit", "Deny", "Indeterminate", "NotApplicable"}; /** * List of obligations which may be empty */ protected List<ObligationResult> obligations; /** * List of advices which may be empty */ protected List<Advice> advices; /** * the decision effect */ protected int decision = -1; /** * the status data */ protected Status status = null; /** * XACML version */ protected int version; /** * Constructs a <code>AbstractResult</code> object with decision status data, obligations, advices * and evaluation ctx * * @param decision the decision effect to include in this result. This must be one of the four * fields in this class. * @param status the <code>Status</code> to include in this result * @param version XACML version * @throws IllegalArgumentException if decision is not valid */ public AbstractResult(int decision, Status status, int version) throws IllegalArgumentException { this.version = version; // check that decision is valid if ((decision != DECISION_PERMIT) && (decision != DECISION_DENY) && (decision != DECISION_INDETERMINATE) && (decision != DECISION_NOT_APPLICABLE) && (decision != DECISION_INDETERMINATE_DENY) && (decision != DECISION_INDETERMINATE_PERMIT) && (decision != DECISION_INDETERMINATE_DENY_OR_PERMIT)) { throw new IllegalArgumentException("invalid decision value"); } this.decision = decision; if (status == null){ this.status = Status.getOkInstance(); } else { this.status = status; } } /** * Constructs a <code>AbstractResult</code> object with decision status data, obligations, advices * and evaluation ctx * * @param decision the decision effect to include in this result. This must be one of the four * fields in this class. * @param status the <code>Status</code> to include in this result * @param obligationResults a list of <code>ObligationResult</code> objects * @param advices a list of <code>Advice</code> objects * @param version XACML version * @throws IllegalArgumentException if decision is not valid */ public AbstractResult(int decision, Status status, List<ObligationResult> obligationResults, List<Advice> advices, int version) throws IllegalArgumentException { this.version = version; // check that decision is valid if ((decision != DECISION_PERMIT) && (decision != DECISION_DENY) && (decision != DECISION_INDETERMINATE) && (decision != DECISION_NOT_APPLICABLE) && (decision != DECISION_INDETERMINATE_DENY) && (decision != DECISION_INDETERMINATE_PERMIT) && (decision != DECISION_INDETERMINATE_DENY_OR_PERMIT)) { throw new IllegalArgumentException("invalid decision value"); } this.decision = decision; if(obligationResults != null){ this.obligations = obligationResults; } if(advices != null){ this.advices = advices; } if (status == null){ this.status = Status.getOkInstance(); } else { this.status = status; } } /** * Returns the set of obligations that the PEP must fulfill, which may be empty. * * @return the set of <code>Obligation</code> */ public List<ObligationResult> getObligations() { if(obligations == null){ obligations = new ArrayList<ObligationResult>(); } return obligations; } /** * Returns the set of advice that the PEP must fulfill, which may be empty. * * @return the set of <code>Advice</code> */ public List<Advice> getAdvices() { if(advices == null){ advices = new ArrayList<Advice>(); } return advices; } /** * Returns the decision associated with this <code>Result</code>. This will be one of the four * <code>DECISION_*</code> fields in this class. * * @return the decision effect */ public int getDecision() { return decision; } /** * Returns the status data included in this <code>Result</code>. Typically this will be * <code>STATUS_OK</code> except when the decision is <code>INDETERMINATE</code>. * * @return status associated with this Result */ public Status getStatus() { return status; } /** * Gets XACML version * * @return XACML version id */ public int getVersion() { return version; } /** * Encodes this <code>AbstractResult</code> into its XML form * * @return <code>String</code> */ public String encode() { StringBuilder builder = new StringBuilder(); encode(builder); return builder.toString(); } /** * Encodes this <code>AbstractResult</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 abstract void encode(StringBuilder builder); }
7,685
29.86747
107
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/ctx/ResultFactory.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.ctx; import org.wso2.balana.ObligationResult; import org.wso2.balana.XACMLConstants; import org.wso2.balana.ctx.xacml3.Result; import org.wso2.balana.xacml3.Advice; import java.util.List; /** * Factory that creates the AbstractResult */ public class ResultFactory { private static volatile ResultFactory factoryInstance; /** * Returns instance of <code>AbstractResult</code> based one the XACML version. * Constructs a <code>AbstractResult</code> object with decision and evaluation ctx * * @param decision decision the decision effect to include in this result. * @param status the <code>Status</code> to include in this result * @param version XACML request version * @return <code>AbstractResult</code> object */ public AbstractResult getResult(int decision, Status status, int version) { if(version == XACMLConstants.XACML_VERSION_3_0){ return new Result(decision, status, null, null, null); } else { return new org.wso2.balana.ctx.xacml2.Result(decision, status); } } /** * Returns instance of <code>AbstractResult</code> based one the XACML version. * Constructs a <code>AbstractResult</code> object with decision and evaluation ctx * * @param decision decision the decision effect to include in this result. * @param evaluationCtx context of a single policy evaluation * @return <code>AbstractResult</code> object */ public AbstractResult getResult(int decision, EvaluationCtx evaluationCtx) { if(evaluationCtx.getXacmlVersion() == XACMLConstants.XACML_VERSION_3_0){ return new Result(decision, null, null, null,evaluationCtx); } else { return new org.wso2.balana.ctx.xacml2.Result(decision, null); } } /** * Returns instance of <code>AbstractResult</code> based one the XACML version. * Constructs a <code>AbstractResult</code> object with decision and evaluation ctx * * @param decision decision the decision effect to include in this result. * @param status the <code>Status</code> to include in this result * @param evaluationCtx context of a single policy evaluation * @return <code>AbstractResult</code> object */ public AbstractResult getResult(int decision, Status status, EvaluationCtx evaluationCtx) { if(evaluationCtx.getXacmlVersion() == XACMLConstants.XACML_VERSION_3_0){ return new Result(decision, status, null, null, evaluationCtx); } else { return new org.wso2.balana.ctx.xacml2.Result(decision, status); } } /** * Returns instance of <code>AbstractResult</code> based one the XACML version. * Constructs a <code>AbstractResult</code> object with decision and evaluation ctx * * @param decision decision the decision effect to include in this result. * @param obligationResults a list of <code>ObligationResult</code> objects * @param advices a list of <code>Advice</code> objects * @param evaluationCtx context of a single policy evaluation * @return <code>AbstractResult</code> object */ public AbstractResult getResult(int decision, List<ObligationResult> obligationResults, List<Advice> advices, EvaluationCtx evaluationCtx) { if(evaluationCtx.getXacmlVersion() == XACMLConstants.XACML_VERSION_3_0){ return new Result(decision, null, obligationResults, advices, evaluationCtx); } else { return new org.wso2.balana.ctx.xacml2.Result(decision, null, obligationResults); } } /** * Returns instance of <code>AbstractResult</code> based one the XACML version. * Constructs a <code>AbstractResult</code> object with decision and evaluation ctx * * @param decision decision the decision effect to include in this result. * @param status the <code>Status</code> to include in this result * @param obligationResults a list of <code>ObligationResult</code> objects * @param advices a list of <code>Advice</code> objects * @param evaluationCtx context of a single policy evaluation * @return <code>AbstractResult</code> object */ public AbstractResult getResult(int decision, Status status, List<ObligationResult> obligationResults, List<Advice> advices, EvaluationCtx evaluationCtx) { if(evaluationCtx.getXacmlVersion() == XACMLConstants.XACML_VERSION_3_0){ return new Result(decision, status,obligationResults, advices, evaluationCtx); } else { return new org.wso2.balana.ctx.xacml2.Result(decision, status, obligationResults); } } /** * Returns an instance of this factory. This method enforces a singleton model, meaning that * this always returns the same instance, creating the factory if it hasn't been requested * before. * * @return the factory instance */ public static ResultFactory getFactory() { if (factoryInstance == null) { synchronized (ResultFactory.class) { if (factoryInstance == null) { factoryInstance = new ResultFactory(); } } } return factoryInstance; } }
6,198
40.604027
106
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/ctx/Attribute.java
/* * @(#)Attribute.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.ctx; import org.wso2.balana.*; import org.wso2.balana.attr.AttributeFactory; import org.wso2.balana.attr.AttributeValue; import org.wso2.balana.attr.DateTimeAttribute; import java.io.PrintStream; import java.io.OutputStream; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Represents the AttributeType XML type found in the context schema. * * @since 1.0 * @author Seth Proctor */ public class Attribute { /** * attribute identifier */ private URI id; /** * attribute data type, this is not used in XACML3 */ private URI type; /** * whether to include this attribute in the result. This is useful to correlate requests * with their responses in case of multiple requests. * optional one defined only in XACML3 */ private boolean includeInResult; /** * issuer of the attribute. optional one */ private String issuer = null; /** * issue instance of the attribute. this is not used in XACML3 */ private DateTimeAttribute issueInstant = null; /** * a <code>List</code> of <code>AttributeValue</code> */ private List<AttributeValue> attributeValues; private int xacmlVersion; /** * Creates a new <code>Attribute</code> of the type specified in the given * <code>AttributeValue</code>.for XACML 3 with one <code>AttributeValue</code> * * @param id the id of the attribute * @param issuer the attribute's issuer or null if there is none * @param issueInstant the moment when the attribute was issued, or null if it's unspecified * @param value the actual value associated with the attribute meta-data * @param includeInResult whether to include this attribute in the result. * @param version XACML version */ public Attribute(URI id, String issuer, DateTimeAttribute issueInstant, AttributeValue value, boolean includeInResult, int version) { this(id, value.getType(), issuer, issueInstant, Arrays.asList(value), includeInResult,version); } /** * Creates a new <code>Attribute</code> for XACML 2 and XACML 1.X with one <code>AttributeValue</code> * * @param id the id of the attribute * @param issuer the attribute's issuer or null if there is none * @param issueInstant the moment when the attribute was issued, or null if it's unspecified * @param value actual <code>List</code> of <code>AttributeValue</code> associated with * @param version XACML version */ public Attribute(URI id, String issuer, DateTimeAttribute issueInstant, AttributeValue value, int version) { this(id, value.getType(), issuer, issueInstant, Arrays.asList(value), false, version); } /** * Creates a new <code>Attribute</code> * * @param id the id of the attribute * @param type the type of the attribute * @param issuer the attribute's issuer or null if there is none * @param issueInstant the moment when the attribute was issued, or null if it's unspecified * @param attributeValues actual <code>List</code> of <code>AttributeValue</code> associated with * @param includeInResult whether to include this attribute in the result. * @param xacmlVersion xacml version */ public Attribute(URI id, URI type, String issuer, DateTimeAttribute issueInstant, List<AttributeValue> attributeValues, boolean includeInResult, int xacmlVersion) { this.id = id; this.type = type; this.issuer = issuer; this.issueInstant = issueInstant; this.attributeValues = attributeValues; this.includeInResult = includeInResult; this.xacmlVersion = xacmlVersion; } /** * Creates an instance of an <code>Attribute</code> based on the root DOM node of the XML data. * * @param root the DOM root of the AttributeType XML type * @param version XACML version * @return the attribute * @throws ParsingException throws ParsingException if the data is invalid */ public static Attribute getInstance(Node root, int version) throws ParsingException { URI id = null; URI type = null; String issuer = null; DateTimeAttribute issueInstant = null; List<AttributeValue> values = new ArrayList<AttributeValue>(); boolean includeInResult = false ; AttributeFactory attributeFactory = Balana.getInstance().getAttributeFactory(); // First check that we're really parsing an Attribute if (!DOMHelper.getLocalName(root).equals("Attribute")) { throw new ParsingException("Attribute object cannot be created " + "with root node of type: " + DOMHelper.getLocalName(root)); } NamedNodeMap attrs = root.getAttributes(); try { id = new URI(attrs.getNamedItem("AttributeId").getNodeValue()); } catch (Exception e) { throw new ParsingException("Error parsing required attribute " + "AttributeId in AttributeType", e); } if(!(version == XACMLConstants.XACML_VERSION_3_0)){ try { type = new URI(attrs.getNamedItem("DataType").getNodeValue()); } catch (Exception e) { throw new ParsingException("Error parsing required attribute " + "DataType in AttributeType", e); } } if(version == XACMLConstants.XACML_VERSION_3_0){ try { String includeInResultString = attrs.getNamedItem("IncludeInResult").getNodeValue(); if("true".equals(includeInResultString)){ includeInResult = true; } } catch (Exception e) { throw new ParsingException("Error parsing required attribute " + "IncludeInResult in AttributeType", e); } } try { Node issuerNode = attrs.getNamedItem("Issuer"); if (issuerNode != null) issuer = issuerNode.getNodeValue(); if(!(version == XACMLConstants.XACML_VERSION_3_0)){ Node instantNode = attrs.getNamedItem("IssueInstant"); if (instantNode != null){ issueInstant = DateTimeAttribute.getInstance(instantNode.getNodeValue()); } } } catch (Exception e) { // shouldn't happen, but just in case... throw new ParsingException("Error parsing optional AttributeType" + " attribute", e); } // now we get the attribute value NodeList nodes = root.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (DOMHelper.getLocalName(node).equals("AttributeValue")) { if(version == XACMLConstants.XACML_VERSION_3_0){ NamedNodeMap dataTypeAttribute = node.getAttributes(); try { type = new URI(dataTypeAttribute.getNamedItem("DataType").getNodeValue()); } catch (Exception e) { throw new ParsingException("Error parsing required attribute " + "DataType in AttributeType", e); } } try { values.add(attributeFactory.createValue(node, type)); } catch (UnknownIdentifierException uie) { throw new ParsingException(uie.getMessage(), uie); } } } // make sure we got a value if (values.size() < 1){ throw new ParsingException("Attribute must contain a value"); } return new Attribute(id, type, issuer, issueInstant, values, includeInResult, version); } /** * Returns the id of this attribute * * @return the attribute id */ public URI getId() { return id; } /** * Returns the data type of this attribute * * @return the attribute's data type */ public URI getType() { return type; } /** * Returns the issuer of this attribute, or null if no issuer was named * * @return the issuer or null */ public String getIssuer() { return issuer; } /** * Returns the moment at which the attribute was issued, or null if no issue time was provided * * @return the time of issuance or null */ public DateTimeAttribute getIssueInstant() { return issueInstant; } /** * Returns whether attribute must be present in response or not * * @return true/false */ public boolean isIncludeInResult() { return includeInResult; } /** * <code>List</code> of <code>AttributeValue</code> of this attribute, * or null if no value was included * * @return the attribute' s value or null */ public List<AttributeValue> getValues() { return attributeValues; } /** * a <code>AttributeValue</code> of this attribute, * or null if no value was included * * @return the attribute' s value or null */ public AttributeValue getValue() { if(attributeValues != null){ return attributeValues.get(0); } return null; } /** * Encodes this <code>Attribute</code> into its XML form * * @return <code>String</code> */ public String encode() { StringBuilder builder = new StringBuilder(); encode(builder); return builder.toString(); } /** * Encodes this <code>Attribute</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("<Attribute AttributeId=\"").append(id.toString()).append("\""); if((xacmlVersion == XACMLConstants.XACML_VERSION_3_0)){ builder.append(" IncludeInResult=\"").append(includeInResult).append("\""); } else { builder.append(" DataType=\"").append(type.toString()).append("\""); if (issueInstant != null){ builder.append(" IssueInstant=\"").append(issueInstant.encode()).append("\""); } } if (issuer != null) { builder.append(" Issuer=\"").append(issuer).append("\""); } builder.append(">\n"); if(attributeValues != null && attributeValues.size() > 0){ for(AttributeValue value : attributeValues){ value.encode(builder); } } builder.append("</Attribute>\n"); } }
12,998
34.227642
107
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/ctx/MissingAttributeDetail.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.ctx; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.balana.*; import org.wso2.balana.attr.AttributeFactory; import org.wso2.balana.attr.AttributeValue; import java.net.URI; import java.util.ArrayList; import java.util.List; /** * This represents the MissingAttributeDetailType in context schema. this contains the information * about attributes required for policy evaluation that were missing from the request context. */ public class MissingAttributeDetail { /** * attribute identifier */ private URI id; /** * attribute data type, this is not used in XACML3 */ private URI type; /** * category of the Attributes element whether it is subject, action and etc */ private URI category; /** * issuer of the attribute. optional one */ private String issuer = null; /** * a <code>List</code> of <code>AttributeValue</code> */ private List<AttributeValue> attributeValues; /** * XACML version */ private int xacmlVersion; /** * Creates a new <code>MissingAttributeDetail</code> * * @param id the id of the attribute * @param type the type of the attribute * @param category category of the attributes elements whether it is subject, action and etc * @param issuer the attribute's issuer or null if there is none * @param attributeValues actual <code>List</code> of <code>AttributeValue</code> * @param xacmlVersion xacml version */ public MissingAttributeDetail(URI id, URI type, URI category, String issuer, List<AttributeValue> attributeValues, int xacmlVersion) { this.id = id; this.type = type; this.category = category; this.issuer = issuer; this.attributeValues = attributeValues; this.xacmlVersion = xacmlVersion; } /** * Creates a new <code>MissingAttributeDetail</code> * * @param id the id of the attribute * @param type the type of the attribute * @param category category of the attributes elements whether it is subject, action and etc * @param attributeValues actual <code>List</code> of <code>AttributeValue</code> * @param xacmlVersion xacml version */ public MissingAttributeDetail(URI id, URI type, URI category, List<AttributeValue> attributeValues, int xacmlVersion) { this(id, type, category, null, attributeValues, xacmlVersion); } /** * Creates a new <code>MissingAttributeDetail</code> * * @param id the id of the attribute * @param type the type of the attribute * @param category category of the attributes elements whether it is subject, action and etc * @param xacmlVersion xacml version */ public MissingAttributeDetail(URI id, URI type, URI category, int xacmlVersion) { this(id, type, category, null, null, xacmlVersion); } /** * Creates an instance of an <code>MissingAttributeDetail</code> based on the root * DOM node of the XML data. * * @param root the DOM root of the AttributeType XML type * @param metaData policy meta data * @return a <code>MissingAttributeDetail</code> object * @throws ParsingException throws ParsingException if the data is invalid */ public static MissingAttributeDetail getInstance(Node root, PolicyMetaData metaData) throws ParsingException { URI id = null; URI type = null; URI category = null; String issuer = null; List<AttributeValue> values = new ArrayList<AttributeValue>(); int version = metaData.getXACMLVersion(); AttributeFactory attrFactory = Balana.getInstance().getAttributeFactory(); // First check that we're really parsing an Attribute if (!DOMHelper.getLocalName(root).equals("MissingAttributeDetail")) { throw new ParsingException("MissingAttributeDetailType object cannot be created " + "with root node of type: " + DOMHelper.getLocalName(root)); } NamedNodeMap attrs = root.getAttributes(); try { id = new URI(attrs.getNamedItem("AttributeId").getNodeValue()); } catch (Exception e) { throw new ParsingException("Error parsing required attribute " + "AttributeId in MissingAttributeDetailType", e); } try { type = new URI(attrs.getNamedItem("DataType").getNodeValue()); } catch (Exception e) { throw new ParsingException("Error parsing required attribute " + "DataType in MissingAttributeDetailType", e); } if(version == XACMLConstants.XACML_VERSION_3_0){ try { category = new URI(attrs.getNamedItem("IncludeInResult").getNodeValue()); } catch (Exception e) { throw new ParsingException("Error parsing required attribute " + "Category in MissingAttributeDetailType", e); } } try { Node issuerNode = attrs.getNamedItem("Issuer"); if (issuerNode != null){ issuer = issuerNode.getNodeValue(); } } catch (Exception e) { // shouldn't happen, but just in case... throw new ParsingException("Error parsing optional attributes in MissingAttributeDetailType", e); } // now we get the attribute value NodeList nodes = root.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (DOMHelper.getLocalName(node).equals("AttributeValue")) { if(version == XACMLConstants.XACML_VERSION_3_0){ NamedNodeMap dataTypeAttribute = node.getAttributes(); try { type = new URI(dataTypeAttribute.getNamedItem("DataType").getNodeValue()); } catch (Exception e) { throw new ParsingException("Error parsing required attribute " + "DataType in MissingAttributeDetailType", e); } } try { values.add(attrFactory.createValue(node, type)); } catch (UnknownIdentifierException uie) { throw new ParsingException("Unknown AttributeValue", uie); } } } return new MissingAttributeDetail(id, type, category, issuer, values, version); } /** * Returns the encoded String from MissingAttributeDetail * * @return String * @throws ParsingException if there are any issues, when parsing object in to Sting */ public String getEncoded() throws ParsingException { if(id == null){ throw new ParsingException("Required AttributeId attribute is Null"); } if(type == null){ throw new ParsingException("Required DataType attribute is Null"); } if(xacmlVersion == XACMLConstants.XACML_VERSION_3_0 && category == null){ throw new ParsingException("Required Category attribute is Null"); } String encoded = "<MissingAttributeDetail AttributeId=\"" + id + "\" DataType=\"" + type + "\""; if(xacmlVersion == XACMLConstants.XACML_VERSION_3_0){ encoded += " Category=\"" + category + "\""; } if(issuer != null){ encoded += " Issuer=\"" + issuer + "\""; } encoded += " >"; if(attributeValues != null && attributeValues.size() > 0){ for(AttributeValue value : attributeValues){ encoded += (value.encodeWithTags(true) + "\n"); } } encoded += "</MissingAttributeDetail>"; return encoded; } }
8,777
34.538462
109
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/ctx/EvaluationCtx.java
/* * @(#)EvaluationCtx.java * * Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.ctx; import org.wso2.balana.xacml3.MultipleCtxResult; import org.wso2.balana.attr.DateAttribute; import org.wso2.balana.attr.DateTimeAttribute; import org.wso2.balana.attr.TimeAttribute; import org.wso2.balana.cond.EvaluationResult; import java.net.URI; import org.w3c.dom.Node; /** * Manages the context of a single policy evaluation. Typically, an instance is instantiated * whenever the PDP gets a request and needs to perform an evaluation as a result. * There are two implementations of <code>XACML3EvaluationCtx</code> class for XACML3 and * <code>XACML3EvaluationCtx</code> for XACML2 * @since 1.0 * @author Seth Proctor */ public interface EvaluationCtx { /** * Returns the DOM root of the original RequestType XML document, if this context is backed by * an XACML Request. If this context is not backed by an XML representation, then an exception * is thrown. * * @return the DOM root node * * @throws UnsupportedOperationException if the context is not backed by an XML representation */ public Node getRequestRoot(); /** * TODO what is this ? * @return */ public boolean isSearching(); /** * Returns the value for the current time as known by the PDP (if this value was also supplied * in the Request, this will generally be a different value). Details of caching or * location-based resolution are left to the underlying implementation. * * @return the current time */ public TimeAttribute getCurrentTime(); /** * Returns the value for the current date as known by the PDP (if this value was also supplied * in the Request, this will generally be a different value). Details of caching or * location-based resolution are left to the underlying implementation. * * @return the current date */ public DateAttribute getCurrentDate(); /** * Returns the value for the current dateTime as known by the PDP (if this value was also * supplied in the Request, this will generally be a different value). Details of caching or * location-based resolution are left to the underlying implementation. * * @return the current date */ public DateTimeAttribute getCurrentDateTime(); /** * Returns available subject attribute value(s). * * @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 getAttribute(URI type, URI id, String issuer, URI category); /** * 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); /** * Returns XACML version of the context * * @return version */ public int getXacmlVersion(); /** * Returns XACML request * * @return <code>AbstractRequestCtx</code> */ public AbstractRequestCtx getRequestCtx(); /** * Returns multiple context results. if, request is combination of multiple requests * * @return <code>MultipleCtxResult</code> */ public MultipleCtxResult getMultipleEvaluationCtx(); }
6,111
37.440252
99
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/ctx/ResponseCtx.java
/* * @(#)ResponseCtx.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.ctx; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.balana.*; import org.wso2.balana.ctx.xacml2.Result; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.io.PrintStream; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; /** * Represents the response to a request made to the XACML PDP. * * @since 1.0 * @author Seth Proctor * @author Marco Barreno */ public class ResponseCtx { // The set of Result objects returned by the PDP private Set<AbstractResult> results = new HashSet<AbstractResult>(); // XACML version private int version; /** * Constructor that creates a new <code>ResponseCtx</code> with only a single * <code>Result</code> (a common case). * * @param result the single result in the response */ public ResponseCtx(AbstractResult result) { this.version = result.getVersion(); results.add(result); } /** * Constructor that creates a new <code>ResponseCtx</code> with a <code>Set</code> of * <code>Result</code>s. The <code>Set</code> must be non-empty. * * @param results a <code>Set</code> of <code>Result</code> objects * @param version XACML version */ public ResponseCtx(Set<AbstractResult> results, int version) { this.version = version; this.results = Collections.unmodifiableSet(new HashSet<AbstractResult>(results)); } /** * Creates a new instance of <code>ResponseCtx</code> based on the given * DOM root node. A <code>ParsingException</code> is thrown if the DOM * root doesn't represent a valid ResponseType. * * @param root the DOM root of a ResponseType * @return a new <code>ResponseCtx</code> * @throws ParsingException if the node is invalid */ public static ResponseCtx getInstance(Node root) throws ParsingException { String requestCtxNs = root.getNamespaceURI(); if(requestCtxNs != null){ if(XACMLConstants.REQUEST_CONTEXT_3_0_IDENTIFIER.equals(requestCtxNs.trim())){ return getInstance(root, XACMLConstants.XACML_VERSION_3_0); } else if(XACMLConstants.REQUEST_CONTEXT_1_0_IDENTIFIER.equals(requestCtxNs.trim()) || XACMLConstants.REQUEST_CONTEXT_2_0_IDENTIFIER.equals(requestCtxNs.trim())) { return getInstance(root, XACMLConstants.XACML_VERSION_2_0); } else { throw new ParsingException("Invalid namespace in XACML response"); } } else { //No Namespace defined in XACML request and Assume as XACML 3.0 return getInstance(root, XACMLConstants.XACML_VERSION_3_0); } } /** * Creates a new instance of <code>ResponseCtx</code> based on the given * DOM root node. A <code>ParsingException</code> is thrown if the DOM * root doesn't represent a valid ResponseType. * * @param root the DOM root of a ResponseType * @param version XACML version * @return a new <code>ResponseCtx</code> * @throws ParsingException if the node is invalid */ public static ResponseCtx getInstance(Node root, int version) throws ParsingException { Set<AbstractResult> results = new HashSet<AbstractResult>(); NodeList nodes = root.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (DOMHelper.getLocalName(node).equals("Result")) { if(version == XACMLConstants.XACML_VERSION_3_0){ results.add(org.wso2.balana.ctx.xacml3.Result.getInstance(node)); } else { results.add(Result.getInstance(node)); } } } if (results.size() == 0){ throw new ParsingException("must have at least one Result"); } return new ResponseCtx(results, version); } /** * Get the set of <code>Result</code>s from this response. * * @return a <code>Set</code> of results */ public Set<AbstractResult> getResults() { return results; } /** * Encodes this <code>ResponseCtx</code> into its XML form * * @return <code>String</code> */ public String encode() { StringBuilder builder = new StringBuilder(); encode(builder); return builder.toString(); } /** * Encodes this <code>ResponseCtx</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("<Response"); if(version == XACMLConstants.XACML_VERSION_3_0){ builder.append(" xmlns=\"urn:oasis:names:tc:xacml:3.0:core:schema:wd-17\""); } builder.append(">"); // Go through all results Iterator it = results.iterator(); while (it.hasNext()) { AbstractResult result = (AbstractResult) (it.next()); result.encode(builder); } // Finish the XML for a response builder.append("</Response>"); } }
7,176
35.247475
98
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/ctx/InputParser.java
/* * @(#)InputParser.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.ctx; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.balana.ParsingException; import java.io.File; import java.io.InputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.balana.utils.Utils; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * A package-private helper that provides a single static routine for parsing input based on the * context schema. * * @since 1.0 * @author Seth Proctor */ public class InputParser implements ErrorHandler { // the schema file, if provided private File schemaFile; // the single reference, which is null unless a schema file is provided private static InputParser ipReference = null; // the property string to set to turn on validation private static final String CONTEXT_SCHEMA_PROPERTY = "com.sun.xacml.ContextSchema"; // the logger we'll use for all messages private static final Log logger = LogFactory.getLog(InputParser.class); // standard strings for setting validation private static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage"; private static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema"; private static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource"; /** * Look for the property that names the schema, and if it exists get the file name and create a * single InputParser instance */ static { String schemaName = System.getProperty(CONTEXT_SCHEMA_PROPERTY); if (schemaName != null) ipReference = new InputParser(new File(schemaName)); }; /** * Constructor that takes the schema file. */ private InputParser(File schemaFile) { this.schemaFile = schemaFile; } /** * Tries to Parse the given output as a Context document. * * @param input the stream to parse * @param rootTage either "Request" or "Response" * * @return the root node of the request/response * * @throws ParsingException if a problem occurred parsing the document */ public static Node parseInput(InputStream input, String rootTag) throws ParsingException { NodeList nodes = null; try { DocumentBuilderFactory factory = Utils.getSecuredDocumentBuilderFactory(); factory.setIgnoringComments(true); DocumentBuilder builder = null; // as of 1.2, we always are namespace aware factory.setNamespaceAware(true); if (ipReference == null) { // we're not validating factory.setValidating(false); builder = factory.newDocumentBuilder(); } else { // we are validating factory.setValidating(true); factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); factory.setAttribute(JAXP_SCHEMA_SOURCE, ipReference.schemaFile); builder = factory.newDocumentBuilder(); builder.setErrorHandler(ipReference); } Document doc = builder.parse(input); nodes = doc.getElementsByTagName(rootTag); } catch (Exception e) { throw new ParsingException("Error tring to parse " + rootTag + "Type", e); } if (nodes.getLength() != 1) throw new ParsingException("Only one " + rootTag + "Type allowed " + "at the root of a Context doc"); return nodes.item(0); } /** * Standard handler routine for the XML parsing. * * @param exception information on what caused the problem */ public void warning(SAXParseException exception) throws SAXException { if (logger.isWarnEnabled()) logger.warn("Warning on line " + exception.getLineNumber() + ": " + exception.getMessage()); } /** * Standard handler routine for the XML parsing. * * @param exception information on what caused the problem * * @throws SAXException always to halt parsing on errors */ public void error(SAXParseException exception) throws SAXException { if (logger.isErrorEnabled()) logger.error("Error on line " + exception.getLineNumber() + ": " + exception.getMessage()); throw new SAXException("invalid context document"); } /** * Standard handler routine for the XML parsing. * * @param exception information on what caused the problem * * @throws SAXException always to halt parsing on errors */ public void fatalError(SAXParseException exception) throws SAXException { if (logger.isErrorEnabled()) logger.error("FatalError on line " + exception.getLineNumber() + ": " + exception.getMessage()); throw new SAXException("invalid context document"); } }
7,051
34.796954
112
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/ctx/EvaluationCtxFactory.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.ctx; import org.wso2.balana.PDPConfig; import org.wso2.balana.ParsingException; import org.wso2.balana.ctx.xacml2.XACML2EvaluationCtx; import org.wso2.balana.ctx.xacml3.RequestCtx; import org.wso2.balana.ctx.xacml3.XACML3EvaluationCtx; import org.wso2.balana.XACMLConstants; /** * Factory that creates the EvaluationCtx */ public class EvaluationCtxFactory { /** * factory instance */ private static volatile EvaluationCtxFactory factoryInstance; public EvaluationCtx getEvaluationCtx(AbstractRequestCtx requestCtx, PDPConfig pdpConfig) throws ParsingException { if(XACMLConstants.XACML_VERSION_3_0 == requestCtx.getXacmlVersion()){ return new XACML3EvaluationCtx((RequestCtx)requestCtx, pdpConfig); } else { return new XACML2EvaluationCtx((org.wso2.balana.ctx.xacml2.RequestCtx) requestCtx, pdpConfig); } } /** * Returns an instance of this factory. This method enforces a singleton model, meaning that * this always returns the same instance, creating the factory if it hasn't been requested * before. * * @return the factory instance */ public static EvaluationCtxFactory getFactory() { if (factoryInstance == null) { synchronized (EvaluationCtxFactory.class) { if (factoryInstance == null) { factoryInstance = new EvaluationCtxFactory(); } } } return factoryInstance; } }
2,264
31.826087
106
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/ctx/xacml3/Result.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.ctx.xacml3; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.balana.*; import org.wso2.balana.ctx.Attribute; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.ctx.AbstractResult; import org.wso2.balana.ctx.Status; import org.wso2.balana.xacml3.Advice; import org.wso2.balana.xacml3.Attributes; import org.wso2.balana.xacml3.Obligation; import java.io.OutputStream; import java.io.PrintStream; import java.util.*; /** * XACML 3 implementation of <code>AbstractResult</code> */ public class Result extends AbstractResult{ /** * Set of applicable policy references */ Set<PolicyReference> policyReferences; /** * Set of attributes that returns to PEP. mainly used in multiple decision profile */ Set<Attributes> attributes; public Result(int decision, Status status){ super(decision, status, XACMLConstants.XACML_VERSION_3_0); } /** * * @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()); } } /** * * @param decision * @param status * @param obligationResults * @param advices * @param policyReferences * @param attributes * @throws IllegalArgumentException */ public Result(int decision, Status status, List<ObligationResult> obligationResults, List<Advice> advices, Set<PolicyReference> policyReferences, Set<Attributes> attributes) throws IllegalArgumentException { super(decision, status, obligationResults, advices, XACMLConstants.XACML_VERSION_3_0); this.policyReferences = policyReferences; processAttributes(attributes); } /** * 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); } /** * Helper method that handles the obligations * * @param root the DOM root of the ObligationsType XML type * @return a <code>List</code> of <code>ObligationResult</code> * @throws ParsingException if any issues in parsing DOM */ private static List<ObligationResult> parseObligations(Node root) throws ParsingException { List<ObligationResult> list = new ArrayList<ObligationResult>(); NodeList nodes = root.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (DOMHelper.getLocalName(node).equals("Obligation")){ list.add(Obligation.getInstance(node)); } } if (list.size() == 0) { throw new ParsingException("ObligationsType must not be empty"); } return list; } /** * Helper method that handles the Advices * * @param root the DOM root of the AssociatedAdviceType XML type * @return a <code>List</code> of <code>Advice</code> * @throws ParsingException if any issues in parsing DOM */ private static List<Advice> parseAdvices(Node root) throws ParsingException { List<Advice> list = new ArrayList<Advice>(); NodeList nodes = root.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (DOMHelper.getLocalName(node).equals("Advice")){ list.add(Advice.getInstance(node)); } } if (list.size() == 0) { throw new ParsingException("AssociatedAdviceType must not be empty"); } return list; } /** * Helper method that handles the Advices * * @param root the DOM root of the PolicyIdentifierListType XML type * @return a <code>Set</code> of <code>PolicyReference</code> * @throws ParsingException if any issues in parsing DOM */ private static Set<PolicyReference> parsePolicyReferences(Node root) throws ParsingException { Set<PolicyReference> set = new HashSet<PolicyReference>(); NodeList nodes = root.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); set.add(PolicyReference.getInstance(node, null, null)); } return set; } /** * Return set of attributes that is sent to PEP * * @return set of attributes */ public Set<Attributes> getAttributes() { return attributes; } /** * Extract the attributes that must be included in the response * * @param attributesSet a <code>Set</code> of <code>Attributes</code> */ public void processAttributes(Set<Attributes> attributesSet){ if(attributesSet == null){ return; } Set<Attributes> newSet = new HashSet<Attributes>(); for(Attributes attributes : attributesSet){ Set<Attribute> attributeSet = attributes.getAttributes(); if(attributeSet == null){ continue; } Set<Attribute> newAttributeSet = new HashSet<Attribute>(); for(Attribute attribute : attributeSet){ if(attribute.isIncludeInResult()){ newAttributeSet.add(attribute); } } if(newAttributeSet.size() > 0){ Attributes newAttributes = new Attributes(attributes.getCategory(), attributes.getContent(), newAttributeSet, attributes.getId()); newSet.add(newAttributes); } } this.attributes = newSet; } /** * Encodes this <code>Result</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("<Result>"); // encode the decision //check whether decision is extended indeterminate values if(decision == 4 || decision == 5 || decision == 6){ // if this is extended indeterminate values, we just return the "Indeterminate" builder.append("<Decision>").append(DECISIONS[2]).append("</Decision>"); } else { builder.append("<Decision>").append(DECISIONS[decision]).append("</Decision>"); } // encode the status if (status != null){ status.encode(builder); } // encode the obligations if (obligations != null && obligations.size() != 0) { builder.append("<Obligations>"); Iterator it = obligations.iterator(); while (it.hasNext()) { Obligation obligation = (Obligation) (it.next()); obligation.encode(builder); } builder.append("</Obligations>"); } // encode the advices if (advices != null && advices.size() != 0) { builder.append("<AssociatedAdvice>"); Iterator it = advices.iterator(); while (it.hasNext()) { Advice advice = (Advice) (it.next()); advice.encode(builder); } builder.append("</AssociatedAdvice>"); } // encode the policy, policySet references if (policyReferences != null && policyReferences.size() != 0) { builder.append("<PolicyIdentifierList>"); for(PolicyReference reference : policyReferences){ reference.encode(builder); } builder.append("</PolicyIdentifierList>"); } // encode the attributes if (attributes != null && attributes.size() != 0) { for(Attributes attribute : attributes){ attribute.encode(builder); } } // finish it off builder.append("</Result>"); } }
11,976
33.416667
106
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/ctx/xacml3/XACML3EvaluationCtx.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.ctx.xacml3; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.balana.*; import org.wso2.balana.attr.*; import org.wso2.balana.attr.xacml3.XPathAttribute; import org.wso2.balana.cond.EvaluationResult; import org.wso2.balana.ctx.*; import org.wso2.balana.finder.ResourceFinderResult; import org.wso2.balana.xacml3.*; import javax.xml.namespace.NamespaceContext; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import java.net.URI; import java.net.URISyntaxException; import java.util.*; /** * This is implementation of XACML3 evaluation context * */ public class XACML3EvaluationCtx extends BasicEvaluationCtx { /** * Attributes set of the request */ private Set<Attributes> attributesSet; /** * multiple content selectors. */ private Set<Attributes> multipleContentSelectors; /** * whether multiple attributes are present or not */ private boolean multipleAttributes; /** * Set of policy references */ private Set<PolicyReference> policyReferences; /** * attributes categorized as Map * * Category --> Attributes Set */ private Map<String, List<Attributes>> mapAttributes; /** * XACML3 request */ private RequestCtx requestCtx; /** * XACML3 request scope. used with multiple resource profile */ private Attribute resourceScopeAttribute; /** * XACML3 request scope. used with hierarchical resource */ private int resourceScope; /** * XACML 3 request resource id. used with hierarchical resource */ private Attribute resourceId; /** * logger */ private static final Log logger = LogFactory.getLog(XACML3EvaluationCtx.class); /** * Creates a new <code>XACML3EvaluationCtx</code> * * @param requestCtx XACML3 RequestCtx * @param pdpConfig PDP configurations */ public XACML3EvaluationCtx(RequestCtx requestCtx, PDPConfig pdpConfig) { // initialize the cached date/time values so it's clear we haven't // retrieved them yet currentDate = null; currentTime = null; currentDateTime = null; mapAttributes = new HashMap<String, List<Attributes>> (); attributesSet = requestCtx.getAttributesSet(); this.pdpConfig = pdpConfig; this.requestCtx = requestCtx; setupAttributes(attributesSet, mapAttributes); } 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)); } 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)); } public int getXacmlVersion() { return requestCtx.getXacmlVersion(); } /** * Generic routine for resource, attribute and environment attributes to build the lookup map * for each. The Form is a Map that is indexed by the String form of the category ids, and that * contains Sets at each entry with all attributes that have that id * * @param attributeSet * @param mapAttributes * @return */ private void setupAttributes(Set<Attributes> attributeSet, Map<String, List<Attributes>> mapAttributes) { for (Attributes attributes : attributeSet) { String category = attributes.getCategory().toString(); for(Attribute attribute : attributes.getAttributes()){ if(XACMLConstants.RESOURCE_CATEGORY.equals(category)){ if(XACMLConstants.RESOURCE_SCOPE_2_0.equals(attribute.getId().toString())){ resourceScopeAttribute = attribute; AttributeValue value = attribute.getValue(); if (value instanceof StringAttribute) { String scope = ((StringAttribute) value).getValue(); if (scope.equals("Children")) { resourceScope = XACMLConstants.SCOPE_CHILDREN; } else if (scope.equals("Descendants")) { resourceScope = XACMLConstants.SCOPE_DESCENDANTS; } } else { logger.error("scope attribute must be a string"); //TODO //throw new ParsingException("scope attribute must be a string"); } } if (XACMLConstants.RESOURCE_ID.equals(attribute.getId().toString())){ if(resourceId == null) { //TODO when there are more than one resource ids?? resourceId = attribute; } } } if(attribute.getId().toString().equals(XACMLConstants.MULTIPLE_CONTENT_SELECTOR)){ if(multipleContentSelectors == null){ multipleContentSelectors = new HashSet<Attributes>(); } multipleContentSelectors.add(attributes); } } if (mapAttributes.containsKey(category)) { List<Attributes> set = mapAttributes.get(category); set.add(attributes); multipleAttributes = true; } else { List<Attributes> set = new ArrayList<Attributes>(); set.add(attributes); mapAttributes.put(category, set); } } } public MultipleCtxResult getMultipleEvaluationCtx() { Set<EvaluationCtx> evaluationCtxSet = new HashSet<EvaluationCtx>(); MultiRequests multiRequests = requestCtx.getMultiRequests(); // 1st check whether there is a multi request attribute if(multiRequests != null){ MultipleCtxResult result = processMultiRequestElement(this); if(result.isIndeterminate()){ return result; } else { evaluationCtxSet.addAll(result.getEvaluationCtxSet()); } } // 2nd check repeated values for category attribute if(evaluationCtxSet.size() > 0){ Set<EvaluationCtx> newSet = new HashSet<EvaluationCtx>(evaluationCtxSet); for(EvaluationCtx evaluationCtx : newSet){ if(((XACML3EvaluationCtx)evaluationCtx).isMultipleAttributes()){ evaluationCtxSet.remove(evaluationCtx); MultipleCtxResult result = processMultipleAttributes((XACML3EvaluationCtx)evaluationCtx); if(result.isIndeterminate()){ return result; } else { evaluationCtxSet.addAll(result.getEvaluationCtxSet()); } } } } else { if(multipleAttributes){ MultipleCtxResult result = processMultipleAttributes(this); if(result.isIndeterminate()){ return result; } else { evaluationCtxSet.addAll(result.getEvaluationCtxSet()); } } } // 3rd check for both scope and multiple-content-selector attributes. Spec does not mention // which one to pick when both are present, there for high priority has given to scope // attribute if(evaluationCtxSet.size() > 0){ Set<EvaluationCtx> newSet = new HashSet<EvaluationCtx>(evaluationCtxSet); for(EvaluationCtx evaluationCtx : newSet){ if(((XACML3EvaluationCtx)evaluationCtx).getResourceScope() != XACMLConstants.SCOPE_IMMEDIATE){ evaluationCtxSet.remove(evaluationCtx); MultipleCtxResult result = processHierarchicalAttributes((XACML3EvaluationCtx)evaluationCtx); if(result.isIndeterminate()){ return result; } else { evaluationCtxSet.addAll(result.getEvaluationCtxSet()); } } else if(((XACML3EvaluationCtx)evaluationCtx).getMultipleContentSelectors() != null){ MultipleCtxResult result = processMultipleContentSelectors((XACML3EvaluationCtx)evaluationCtx); if(result.isIndeterminate()){ return result; } else { evaluationCtxSet.addAll(result.getEvaluationCtxSet()); } } } } else { if(resourceScope != XACMLConstants.SCOPE_IMMEDIATE){ MultipleCtxResult result = processHierarchicalAttributes(this); if(result.isIndeterminate()){ return result; } else { evaluationCtxSet.addAll(result.getEvaluationCtxSet()); } } else if(multipleContentSelectors != null){ MultipleCtxResult result = processMultipleContentSelectors(this); if(result.isIndeterminate()){ return result; } else { evaluationCtxSet.addAll(result.getEvaluationCtxSet()); } } } if(evaluationCtxSet.size() > 0){ return new MultipleCtxResult(evaluationCtxSet); } else { evaluationCtxSet.add(this); return new MultipleCtxResult(evaluationCtxSet); } } /** * Process multi request element * * @param evaluationCtx <code>XACML3EvaluationCtx</code> * @return <code>MultipleCtxResult</code> */ private MultipleCtxResult processMultiRequestElement(XACML3EvaluationCtx evaluationCtx) { Set<EvaluationCtx> children = new HashSet<EvaluationCtx>(); MultiRequests multiRequests = requestCtx.getMultiRequests(); if(multiRequests == null){ return new MultipleCtxResult(children); } Set<RequestReference> requestReferences = multiRequests.getRequestReferences(); for(RequestReference reference : requestReferences) { Set<AttributesReference> attributesReferences = reference.getReferences(); if(attributesReferences != null && attributesReferences.size() > 0){ Set<Attributes> attributes = new HashSet<Attributes>(); for(AttributesReference attributesReference : attributesReferences){ String referenceId = attributesReference.getId(); if(referenceId != null){ Attributes newAttributes = null; for(Attributes attribute : evaluationCtx.getAttributesSet()){ // check equal with reference id if(attribute.getId() != null && attribute.getId().equals(referenceId)){ newAttributes = attribute; } } if(newAttributes != null){ attributes.add(newAttributes); } else { // This must be only for one result. But here it is used to create error for List<String> code = new ArrayList<String>(); code.add(Status.STATUS_SYNTAX_ERROR); return new MultipleCtxResult(new Status(code, "Invalid reference to attributes")); } } } RequestCtx ctx = new RequestCtx(attributes, null); children.add(new XACML3EvaluationCtx(ctx, pdpConfig)); } } return new MultipleCtxResult(children); } /** * Process multiple attributes with same category * * @param evaluationCtx <code>XACML3EvaluationCtx</code> * @return <code>MultipleCtxResult</code> */ private MultipleCtxResult processMultipleAttributes(XACML3EvaluationCtx evaluationCtx) { Set<EvaluationCtx> children = new HashSet<EvaluationCtx>(); Map<String, List<Attributes>> mapAttributes = evaluationCtx.getMapAttributes(); Set<Set<Attributes>> tempRequestAttributes = new HashSet<Set<Attributes>>(Arrays.asList(evaluationCtx.getAttributesSet())); for(Map.Entry<String, List<Attributes>> mapAttributesEntry : mapAttributes.entrySet()){ if(mapAttributesEntry.getValue().size() > 1){ Set<Set<Attributes>> temp = new HashSet<Set<Attributes>>(); for(Attributes attributesElement : mapAttributesEntry.getValue()){ for(Set<Attributes> tempRequestAttribute : tempRequestAttributes){ Set<Attributes> newSet = new HashSet<Attributes>(tempRequestAttribute); newSet.removeAll(mapAttributesEntry.getValue()); newSet.add(attributesElement); temp.add(newSet); } } tempRequestAttributes = temp; } } for(Set<Attributes> ctx : tempRequestAttributes){ RequestCtx requestCtx = new RequestCtx(ctx, null); children.add(new XACML3EvaluationCtx(requestCtx, pdpConfig)); } return new MultipleCtxResult(children); } /** * * @param evaluationCtx * @return */ private MultipleCtxResult processHierarchicalAttributes(XACML3EvaluationCtx evaluationCtx) { ResourceFinderResult resourceResult = null; Set<EvaluationCtx> children = new HashSet<EvaluationCtx>(); Attribute resourceId = evaluationCtx.getResourceId(); if(resourceId != null){ if(evaluationCtx.getResourceScope() == XACMLConstants.SCOPE_CHILDREN){ resourceResult = pdpConfig.getResourceFinder(). findChildResources(resourceId.getValue(), evaluationCtx); } else if(evaluationCtx.getResourceScope() == XACMLConstants.SCOPE_DESCENDANTS) { resourceResult = pdpConfig.getResourceFinder(). findDescendantResources(resourceId.getValue(), evaluationCtx); } else { logger.error("Unknown scope type: " ); //TODO } } else { logger.error("ResourceId Attribute is NULL: " ); // TODO } if(resourceResult == null || resourceResult.isEmpty()){ logger.error("Resource Finder result is NULL: " ); // TODO } else { for (AttributeValue resource : resourceResult.getResources()) { Set<Attributes> newSet = new HashSet<Attributes>(evaluationCtx.getAttributesSet()); Attributes resourceAttributes = null; for(Attributes attributes : newSet){ if(XACMLConstants.RESOURCE_CATEGORY.equals(attributes.getCategory().toString())){ Set<Attribute> attributeSet = new HashSet<Attribute>(attributes.getAttributes()); attributeSet.remove(resourceScopeAttribute); attributeSet.remove(resourceId); try{ Attribute attribute = new Attribute(new URI(XACMLConstants.RESOURCE_ID), resourceId.getIssuer(), null, resource, resourceId.isIncludeInResult(), XACMLConstants.XACML_VERSION_3_0); attributeSet.add(attribute); Attributes newAttributes = new Attributes(new URI(XACMLConstants.RESOURCE_CATEGORY), (Node)attributes.getContent(), attributeSet, attributes.getId()); newSet.add(newAttributes); resourceAttributes = attributes; } catch (URISyntaxException e) { //ignore } break; } } if(resourceAttributes != null){ newSet.remove(resourceAttributes); children.add(new XACML3EvaluationCtx(new RequestCtx(newSet, null), pdpConfig)); } } } return new MultipleCtxResult(children); } /** * * @param evaluationCtx * @return */ private MultipleCtxResult processMultipleContentSelectors(XACML3EvaluationCtx evaluationCtx) { Set<EvaluationCtx> children = new HashSet<EvaluationCtx>(); Set<Attributes> newAttributesSet = new HashSet<Attributes>(); for(Attributes attributes : evaluationCtx.getMultipleContentSelectors()){ Set<Attribute> newAttributes = null; Attribute oldAttribute = null; Object content = attributes.getContent(); if(content != null && content instanceof Node){ Node root = (Node) content; for(Attribute attribute : attributes.getAttributes()){ oldAttribute = attribute; if(attribute.getId().toString().equals(XACMLConstants.MULTIPLE_CONTENT_SELECTOR)){ List<AttributeValue> values = attribute.getValues(); for(AttributeValue value : values){ if(value instanceof XPathAttribute){ XPathAttribute xPathAttribute = (XPathAttribute)value; if(xPathAttribute.getXPathCategory(). equals(attributes.getCategory().toString())){ Set<String> xPaths = getChildXPaths(root, xPathAttribute.getValue()); for(String xPath : xPaths){ try { AttributeValue newValue = Balana.getInstance().getAttributeFactory(). createValue(value.getType(), xPath, new String[] {xPathAttribute.getXPathCategory()}); Attribute newAttribute = new Attribute(new URI(XACMLConstants.CONTENT_SELECTOR), attribute.getIssuer(), attribute.getIssueInstant(), newValue, attribute.isIncludeInResult(), XACMLConstants.XACML_VERSION_3_0); if(newAttributes == null){ newAttributes = new HashSet<Attribute>(); } newAttributes.add(newAttribute); } catch (Exception e) { logger.error(e); // TODO } } } } } } } if(newAttributes != null){ attributes.getAttributes().remove(oldAttribute); for(Attribute attribute : newAttributes){ Set<Attribute> set = new HashSet<Attribute>(attributes.getAttributes()); set.add(attribute); Attributes attr = new Attributes(attributes.getCategory(), attributes.getContent(), set, attributes.getId()); newAttributesSet.add(attr); } evaluationCtx.getAttributesSet().remove(attributes); } } } for(Attributes attributes : newAttributesSet){ Set<Attributes> set = new HashSet<Attributes>(evaluationCtx.getAttributesSet()); set.add(attributes); RequestCtx requestCtx = new RequestCtx(set, null); children.add(new XACML3EvaluationCtx(requestCtx, pdpConfig)); } return new MultipleCtxResult(children); } /** * Changes the value of the resource-id attribute in this context. This is useful when you have * multiple resources (ie, a scope other than IMMEDIATE), and you need to keep changing only the * resource-id to evaluate the different effective requests. * * @param resourceId resourceId the new resource-id value * @param attributesSet a <code>Set</code> of <code>Attributes</code> */ public void setResourceId(AttributeValue resourceId, Set<Attributes> attributesSet) { for(Attributes attributes : attributesSet){ if(XACMLConstants.RESOURCE_CATEGORY.equals(attributes.getCategory().toString())){ Set<Attribute> attributeSet = attributes.getAttributes(); Set<Attribute> newSet = new HashSet<Attribute>(attributeSet); Attribute resourceIdAttribute = null; for (Attribute attribute : newSet){ if(XACMLConstants.RESOURCE_ID.equals(attribute.getId().toString())){ resourceIdAttribute = attribute; attributeSet.remove(attribute); } else if(XACMLConstants.RESOURCE_SCOPE_2_0.equals(attribute.getId().toString())){ attributeSet.remove(attribute); } } if(resourceIdAttribute != null) { attributeSet.add(new Attribute(resourceIdAttribute.getId(), resourceIdAttribute.getIssuer(), resourceIdAttribute.getIssueInstant(), resourceId, resourceIdAttribute.isIncludeInResult(), XACMLConstants.XACML_VERSION_3_0)); } break; } } } private Set<String> getChildXPaths(Node root, String xPath){ Set<String> xPaths = new HashSet<String>(); NamespaceContext namespaceContext = null; XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); if(namespaceContext == null){ //see if the request root is in a namespace String namespace = null; if(root != null){ namespace = root.getNamespaceURI(); } // name spaces are used, so we need to lookup the correct // prefix to use in the search string NamedNodeMap namedNodeMap = root.getAttributes(); Map<String, String> nsMap = new HashMap<String, String>(); if(namedNodeMap != null){ for (int i = 0; i < namedNodeMap.getLength(); i++) { Node n = namedNodeMap.item(i); // we found the matching namespace, so get the prefix // and then break out String prefix = DOMHelper.getLocalName(n); String nodeValue= n.getNodeValue(); nsMap.put(prefix, nodeValue); } } // if there is not any namespace is defined for content element, default XACML request // name space would be there. if(XACMLConstants.REQUEST_CONTEXT_3_0_IDENTIFIER.equals(namespace) || XACMLConstants.REQUEST_CONTEXT_2_0_IDENTIFIER.equals(namespace) || XACMLConstants.REQUEST_CONTEXT_1_0_IDENTIFIER.equals(namespace)){ nsMap.put("xacml", namespace); } namespaceContext = new DefaultNamespaceContext(nsMap); } xpath.setNamespaceContext(namespaceContext); try { XPathExpression expression = xpath.compile(xPath); NodeList matches = (NodeList) expression.evaluate(root, XPathConstants.NODESET); if(matches != null && matches.getLength() > 0){ for (int i = 0; i < matches.getLength(); i++) { String text = null; Node node = matches.item(i); short nodeType = node.getNodeType(); // see if this is straight text, or a node with data under // it and then get the values accordingly if ((nodeType == Node.CDATA_SECTION_NODE) || (nodeType == Node.COMMENT_NODE) || (nodeType == Node.TEXT_NODE) || (nodeType == Node.ATTRIBUTE_NODE)) { // there is no child to this node text = node.getNodeValue(); } else { // the data is in a child node text = "/" + DOMHelper.getLocalName(node); } String newXPath = '(' + xPath + ")[" + (i+1) + ']'; xPaths.add(newXPath); } } } catch (Exception e) { // TODO } return xPaths; } public boolean isMultipleAttributes() { return multipleAttributes; } public AbstractRequestCtx getRequestCtx() { return requestCtx; } /** * * @return */ public Set<PolicyReference> getPolicyReferences() { return policyReferences; } /** * * @param policyReferences */ public void setPolicyReferences(Set<PolicyReference> policyReferences) { this.policyReferences = policyReferences; } /** * * @param category * @return */ public List<Attributes> getAttributes(String category){ return mapAttributes.get(category); } public Set<Attributes> getMultipleContentSelectors() { return multipleContentSelectors; } public Map<String, List<Attributes>> getMapAttributes() { return mapAttributes; } public Set<Attributes> getAttributesSet() { return attributesSet; } public Attribute getResourceId() { return resourceId; } public int getResourceScope() { return resourceScope; } public Attribute getResourceScopeAttribute() { return resourceScopeAttribute; } }
31,007
40.288948
115
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/ctx/xacml3/RequestCtx.java
/* * @(#)RequestCtx.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.ctx.xacml3; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.balana.DOMHelper; import org.wso2.balana.Indenter; import org.wso2.balana.ParsingException; import org.wso2.balana.XACMLConstants; import org.wso2.balana.ctx.*; import org.wso2.balana.xacml3.Attributes; import org.wso2.balana.xacml3.MultiRequests; import org.wso2.balana.xacml3.RequestDefaults; import java.io.OutputStream; import java.io.PrintStream; import java.util.HashSet; import java.util.Set; /** * Represents a XACML3 request made to the PDP. This is the class that contains all the data used to start * a policy evaluation. */ public class RequestCtx extends AbstractRequestCtx { /** * define boolean value whether to send back the applicable policies to PEP or not */ private boolean returnPolicyIdList; /** * uses for when multiple decisions is enabled in PDP. This is defined whether to combine * multiple decisions or not */ private boolean combinedDecision; /** * lists multiple request contexts by references to the <Attributes> elements */ private MultiRequests multiRequests; /** * contains default values for the request, such as XPath version. */ private RequestDefaults defaults; /** * Constructor that creates a <code>RequestCtx</code> from components. * * @param attributesSet a <code>Set</code> of <code>Attributes</code>s * @param documentRoot the root node of the DOM tree for this request * @throws IllegalArgumentException if the inputs are not well formed */ public RequestCtx(Set<Attributes> attributesSet, Node documentRoot) { this(documentRoot, attributesSet, false, false, null, null); } /** * Constructor that creates a <code>RequestCtx</code> from components. * * @param documentRoot the root node of the DOM tree for this request * @param attributesSet a <code>Set</code> of <code>Attributes</code>s * @param returnPolicyIdList a <code>boolean</code> value whether to send back policy list of not * @param combinedDecision a <code>boolean</code> value whether to combine decisions or not * @param multiRequests a <code>MultiRequests</code> for the MultiRequests element in request * @param defaults a <code>RequestDefaults</code> for the RequestDefaults element in request * @throws IllegalArgumentException if the inputs are not well formed */ public RequestCtx(Node documentRoot, Set<Attributes> attributesSet, boolean returnPolicyIdList, boolean combinedDecision, MultiRequests multiRequests, RequestDefaults defaults) throws IllegalArgumentException { this.xacmlVersion = XACMLConstants.XACML_VERSION_3_0; this.documentRoot = documentRoot; this.attributesSet = attributesSet; this.returnPolicyIdList = returnPolicyIdList; this.combinedDecision = combinedDecision; this.multiRequests = multiRequests; this.defaults = defaults; } /** * Create a new <code>RequestCtx</code> by parsing a node. This node should be created by * schema-verified parsing of an <code>XML</code> document. * * @param root the node to parse for the <code>RequestCtx</code> * @return a new <code>RequestCtx</code> constructed by parsing * @throws org.wso2.balana.ParsingException * if the DOM node is invalid */ public static RequestCtx getInstance(Node root) throws ParsingException { Set<Attributes> attributesElements; boolean returnPolicyIdList = false; boolean combinedDecision = false; MultiRequests multiRequests = null; RequestDefaults defaults = null; // First check to be sure the node passed is indeed a Request node. String tagName = DOMHelper.getLocalName(root); if (!tagName.equals("Request")) { throw new ParsingException("Request cannot be constructed using " + "type: " + DOMHelper.getLocalName(root)); } NamedNodeMap attrs = root.getAttributes(); try { String attributeValue = attrs.getNamedItem(XACMLConstants.RETURN_POLICY_LIST). getNodeValue(); if ("true".equals(attributeValue)) { returnPolicyIdList = true; } } catch (Exception e) { throw new ParsingException("Error parsing required attribute " + "ReturnPolicyIdList in RequestType", e); } try { String attributeValue = attrs.getNamedItem(XACMLConstants.COMBINE_DECISION). getNodeValue(); if ("true".equals(attributeValue)) { combinedDecision = true; } } catch (Exception e) { throw new ParsingException("Error parsing required attribute " + "CombinedDecision in RequestType", e); } attributesElements = new HashSet<Attributes>(); NodeList children = root.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node node = children.item(i); String tag = DOMHelper.getLocalName(node); if (tag.equals(XACMLConstants.ATTRIBUTES_ELEMENT)) { Attributes attributes = Attributes.getInstance(node); attributesElements.add(attributes); } if (tag.equals(XACMLConstants.MULTI_REQUESTS)) { if (multiRequests != null) { throw new ParsingException("Too many MultiRequests elements are defined."); } multiRequests = MultiRequests.getInstance(node); } if (tag.equals(XACMLConstants.REQUEST_DEFAULTS)) { if (multiRequests != null) { throw new ParsingException("Too many RequestDefaults elements are defined."); } defaults = RequestDefaults.getInstance(node); } } if (attributesElements.isEmpty()) { throw new ParsingException("Request must contain at least one AttributesType"); } return new RequestCtx(root, attributesElements, returnPolicyIdList, combinedDecision, multiRequests, defaults); } /** * Returns a <code>boolean</code> value whether to combine decisions or not * * @return true of false */ public boolean isCombinedDecision() { return combinedDecision; } /** * Returns a <code>boolean</code> value whether to send back policy list of not * * @return true or false */ public boolean isReturnPolicyIdList() { return returnPolicyIdList; } /** * Returns a <code>MultiRequests</code> that encapsulates MultiRequests element in request * * @return MultiRequests element in request */ public MultiRequests getMultiRequests() { return multiRequests; } /** * Returns a <code>RequestDefaults</code> that encapsulates RequestDefaults element in request * * @return RequestDefaults element in request */ public RequestDefaults getDefaults() { return defaults; } /** * Encodes this <code>AbstractRequestCtx</code> into its XML representation and writes this encoding to the given * <code>OutputStream</code> with indentation. * * @param output a stream into which the XML-encoded data is written * @param indenter an object that creates indentation strings */ public void encode(OutputStream output, Indenter indenter) { String indent = indenter.makeString(); PrintStream out = new PrintStream(output); out.println(indent + "<Request xmlns=\"" + XACMLConstants.REQUEST_CONTEXT_3_0_IDENTIFIER + "\" ReturnPolicyIdList=\"" + returnPolicyIdList + "\" CombinedDecision=\"" + combinedDecision + "\" >"); indenter.in(); for(Attributes attributes : attributesSet){ out.println(attributes.encode()); } if(defaults != null){ defaults.encode(output, indenter); } if(multiRequests != null){ // multiRequests } indenter.out(); out.println(indent + "</Request>"); } /** * Encodes this <code>AbstractRequestCtx</code> into its XML representation and writes this encoding to the given * <code>OutputStream</code>. No indentation is used. * * @param output a stream into which the XML-encoded data is written */ public void encode(OutputStream output) { encode(output, new Indenter(0)); } }
10,666
37.232975
119
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/ctx/xacml2/Result.java
/* * @(#)Result.java * * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.ctx.xacml2; import org.wso2.balana.*; import org.wso2.balana.ctx.AbstractResult; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.ctx.Status; import java.io.OutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.balana.xacml2.Obligation; import org.wso2.balana.xacml3.Advice; /** * XACML 2 and 1 implementation of <code>AbstractResult</code> * */ public class Result extends AbstractResult { /** * the resourceId identifier or null if there is none */ private String resourceId = null; 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); } 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); } 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; } /** * 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); } /** * Helper method that handles the obligations * * @param root the DOM root of the ObligationsType XML type * @return a <code>List</code> of <code>ObligationResult</code> * @throws ParsingException if any issues in parsing DOM */ private static List<ObligationResult> parseObligations(Node root) throws ParsingException { List<ObligationResult> list = new ArrayList<ObligationResult>(); NodeList nodes = root.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (DOMHelper.getLocalName(node).equals("Obligation")){ list.add(Obligation.getInstance(node)); } } if (list.size() == 0){ throw new ParsingException("ObligationsType must not be empty"); } return list; } /** * Returns the resourceId to which this Result applies, or null if none is specified. * * @return a resourceId identifier or null */ public String getResourceId() { return resourceId; } /** * Sets the resourceId identifier if it has not already been set before. The core code does not * set the resourceId identifier, so this is useful if you want to write wrapper code that needs * this information. * * @param resource the resourceId identifier * * @return true if the resourceId identifier was set, false if it already had a value */ public boolean setResource(String resource) { if (this.resourceId != null){ return false; } this.resourceId = resource; return true; } @Override public void encode(StringBuilder builder) { if (resourceId == null){ builder.append("<Result>"); } else { builder.append("<Result ResourceId=\"").append(resourceId).append("\">"); } // encode the decision builder.append("<Decision>").append(DECISIONS[decision]).append("</Decision>"); // encode the status if (status != null){ status.encode(builder); } // encode the obligations if (obligations != null && obligations.size() != 0) { builder.append("<Obligations>"); Iterator it = obligations.iterator(); while (it.hasNext()) { ObligationResult obligation = (ObligationResult) (it.next()); obligation.encode(builder); } builder.append("</Obligations>"); } // finish it off builder.append("</Result>"); } }
8,318
35.169565
100
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/ctx/xacml2/Subject.java
/* * @(#)Subject.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.ctx.xacml2; import org.wso2.balana.attr.AttributeDesignator; import java.net.URI; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** * This class represents the collection of <code>Attribute</code>s associated with a particular * subject. * * @since 1.1 * @author seth proctor */ public class Subject { // the subject's category private URI category; // the attributes associated with the subject private Set attributes; /** * <code>URI</code> form of the default subject category */ public static final URI DEFAULT_CATEGORY; // the exception thrown if the default category was invalid private static RuntimeException earlyException = null; /** * Tries to initialize the default category, keeping track of the exception for later use (if * there was a problem). Note that this should never happen, but the error case will be reported * correctly if the default string is invalid. */ static { URI defaultURI = null; try { defaultURI = new URI(AttributeDesignator.SUBJECT_CATEGORY_DEFAULT); } catch (Exception e) { earlyException = new IllegalArgumentException("invalid URI"); earlyException.initCause(e); } DEFAULT_CATEGORY = defaultURI; } /** * Creates a new collection of subject attributes using the default subject cateorgy. * * @param attributes a non-null <code>Set</code> of <code>Attribute</code> objects */ public Subject(Set attributes) { this(null, attributes); if (earlyException != null) throw earlyException; } /** * Creates a new collection of subject attributes using the given subject category. * * @param category the subject category or null for the default category * @param attributes a non-null <code>Set</code> of <code>Attribute</code> objects */ public Subject(URI category, Set attributes) { if (category == null) this.category = DEFAULT_CATEGORY; else this.category = category; this.attributes = Collections.unmodifiableSet(new HashSet(attributes)); } /** * Returns the category of this subject's attributes. * * @return the category */ public URI getCategory() { return category; } /** * Returns the <code>Attribute</code>s associated with this subject. * * @return the immutable <code>Set</code> of <code>Attribute</code>s */ public Set getAttributes() { return attributes; } }
4,480
32.691729
100
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/ctx/xacml2/XACML2EvaluationCtx.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.ctx.xacml2; import org.wso2.balana.*; import org.wso2.balana.cond.EvaluationResult; import org.wso2.balana.ctx.*; import org.wso2.balana.finder.ResourceFinderResult; import org.wso2.balana.xacml3.Attributes; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.balana.attr.AttributeValue; import org.wso2.balana.attr.BagAttribute; import org.wso2.balana.attr.StringAttribute; import org.wso2.balana.xacml3.MultipleCtxResult; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** * */ public class XACML2EvaluationCtx extends BasicEvaluationCtx { private Set<Attributes> attributesSet; private int xacmlVersion; // the 4 maps that contain the attribute data private HashMap subjectMap; private HashMap resourceMap; private HashMap actionMap; private HashMap environmentMap; // the resource and its scope private AttributeValue resourceId; private int scope; private RequestCtx requestCtx; //private Set<ObligationResult> obligationResults; //private Set<Advice> advices; // the logger we'll use for all messages private static final Log logger = LogFactory.getLog(XACML2EvaluationCtx.class); public XACML2EvaluationCtx() { } public XACML2EvaluationCtx(RequestCtx requestCtx, PDPConfig pdpConfig) throws ParsingException { // keep track of the finder this.pdpConfig = pdpConfig; this.requestCtx = requestCtx; xacmlVersion = requestCtx.getXacmlVersion(); // remember the root of the DOM tree for XPath queries requestRoot = requestCtx.getDocumentRoot(); attributesSet = requestCtx.getAttributesSet(); // initialize the cached date/time values so it's clear we haven't // retrieved them yet this.useCachedEnvValues = false; currentDate = null; currentTime = null; currentDateTime = null; // get the subjects, make sure they're correct, and setup tables subjectMap = new HashMap(); setupSubjects(requestCtx.getSubjects()); // next look at the Resource data, which needs to be handled specially resourceMap = new HashMap(); setupResource(requestCtx.getResource()); // setup the action data, which is generic actionMap = new HashMap(); mapAttributes(requestCtx.getAction(), actionMap); // finally, set up the environment data, which is also generic environmentMap = new HashMap(); mapAttributes(requestCtx.getEnvironmentAttributes(), environmentMap); } /** * This is quick helper function to provide a little structure for the subject attributes so we * can search for them (somewhat) quickly. The basic idea is to have a map indexed by * SubjectCategory that keeps Maps that in turn are indexed by id and keep the unique * ctx.Attribute objects. */ private void setupSubjects(Set subjects) { // now go through the subject attributes Iterator it = subjects.iterator(); while (it.hasNext()) { Subject subject = (Subject) (it.next()); URI category = subject.getCategory(); Map categoryMap = null; // see if we've already got a map for the category if (subjectMap.containsKey(category)) { categoryMap = (Map) (subjectMap.get(category)); } else { categoryMap = new HashMap(); subjectMap.put(category, categoryMap); } // iterate over the set of attributes Iterator attrIterator = subject.getAttributes().iterator(); while (attrIterator.hasNext()) { Attribute attr = (Attribute) (attrIterator.next()); String id = attr.getId().toString(); if (categoryMap.containsKey(id)) { // add to the existing set of Attributes w/this id Set existingIds = (Set) (categoryMap.get(id)); existingIds.add(attr); } else { // this is the first Attr w/this id HashSet newIds = new HashSet(); newIds.add(attr); categoryMap.put(id, newIds); } } } } /** * This basically does the same thing that the other types need to do, except that we also look * for a resource-id attribute, not because we're going to use, but only to make sure that it's * actually there, and for the optional scope attribute, to see what the scope of the attribute * is */ private void setupResource(Set resource) throws ParsingException { mapAttributes(resource, resourceMap); // make sure there resource-id attribute was included if (!resourceMap.containsKey(XACMLConstants.RESOURCE_ID)) { logger.error("Resource must contain resource-id attr"); throw new ParsingException("resource missing resource-id"); } else { // make sure there's only one value for this Set set = (Set) (resourceMap.get(XACMLConstants.RESOURCE_ID)); if (set.size() > 1) { logger.error("Resource may contain only one resource-id Attribute"); throw new ParsingException("too many resource-id attrs"); } else { // keep track of the resource-id attribute resourceId = ((Attribute) (set.iterator().next())).getValue(); } } // see if a resource-scope attribute was included if (resourceMap.containsKey(XACMLConstants.RESOURCE_SCOPE_1_0)) { Set set = (Set) (resourceMap.get(XACMLConstants.RESOURCE_SCOPE_1_0)); // make sure there's only one value for resource-scope if (set.size() > 1) { logger.error("Resource may contain only one resource-scope Attribute"); throw new ParsingException("too many resource-scope attrs"); } Attribute attr = (Attribute) (set.iterator().next()); AttributeValue attrValue = attr.getValue(); // scope must be a string, so throw an exception otherwise if (!attrValue.getType().toString().equals(StringAttribute.identifier)) { logger.error("scope attr must be a string"); throw new ParsingException("scope attr must be a string"); } String value = ((StringAttribute) attrValue).getValue(); if (value.equals("Immediate")) { scope = XACMLConstants.SCOPE_IMMEDIATE; } else if (value.equals("Children")) { scope = XACMLConstants.SCOPE_CHILDREN; } else if (value.equals("Descendants")) { scope = XACMLConstants.SCOPE_DESCENDANTS; } else { logger.error("Unknown scope type: " + value); throw new ParsingException("invalid scope type: " + value); } } else { // by default, the scope is always Immediate scope = XACMLConstants.SCOPE_IMMEDIATE; } } /** * Generic routine for resource, attribute and environment attributes to build the lookup map * for each. The Form is a Map that is indexed by the String form of the attribute ids, and that * contains Sets at each entry with all attributes that have that id */ private void mapAttributes(Set input, Map output) { Iterator it = input.iterator(); while (it.hasNext()) { Attribute attr = (Attribute) (it.next()); String id = attr.getId().toString(); if (output.containsKey(id)) { Set set = (Set) (output.get(id)); set.add(attr); } else { Set set = new HashSet(); set.add(attr); output.put(id, set); } } } /** * Returns the resource scope of the request, which will be one of the three fields denoting * Immediate, Children, or Descendants. * * @return the scope of the resource in the request */ public int getScope() { return scope; } /** * Returns the resource named in the request as resource-id. * * @return the resource */ public AttributeValue getResourceId() { return resourceId; } /** * Changes the value of the resource-id attribute in this context. This is useful when you have * multiple resources (ie, a scope other than IMMEDIATE), and you need to keep changing only the * resource-id to evaluate the different effective requests. * * @param resourceId the new resource-id value */ public void setResourceId(AttributeValue resourceId, Set<Attributes> attributesSet) { this.resourceId = resourceId; // there will always be exactly one value for this attribute Set attrSet = (Set) (resourceMap.get(XACMLConstants.RESOURCE_ID)); Attribute attr = (Attribute) (attrSet.iterator().next()); // remove the old value... attrSet.remove(attr); // ...and insert the new value attrSet.add(new Attribute(attr.getId(), attr.getIssuer(), attr.getIssueInstant(), resourceId,XACMLConstants.XACML_VERSION_2_0)); } 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); } } public int getXacmlVersion() { return xacmlVersion; } /** * 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); } /** * Returns attribute value(s) from the resource 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 * @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 getResourceAttribute(URI type, URI id, URI category, String issuer) { return getGenericAttributes(type, id, category, issuer, resourceMap); } /** * Returns attribute value(s) from the action 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 * @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 getActionAttribute(URI type, URI id, URI category, String issuer) { return getGenericAttributes(type, id, category, issuer, actionMap); } /** * Returns attribute value(s) from the environment 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 * @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 getEnvironmentAttribute(URI type, URI id, URI category, String issuer) { return getGenericAttributes(type, id, category, issuer, environmentMap); } /** * 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)); } public PDPConfig getPdpConfig() { return pdpConfig; } public AbstractRequestCtx getRequestCtx() { return requestCtx; } public MultipleCtxResult getMultipleEvaluationCtx() { Set<EvaluationCtx> evaluationCtxSet = new HashSet<EvaluationCtx>(); if(scope != XACMLConstants.SCOPE_IMMEDIATE){ MultipleCtxResult result = processHierarchicalAttributes(this); if(result.isIndeterminate()){ return result; } else { evaluationCtxSet.addAll(result.getEvaluationCtxSet()); } } if(evaluationCtxSet.size() > 0){ return new MultipleCtxResult(evaluationCtxSet, null, false); } else { evaluationCtxSet.add(this); return new MultipleCtxResult(evaluationCtxSet, null, false); } } public int getResourceScope() { return scope; } private MultipleCtxResult processHierarchicalAttributes(XACML2EvaluationCtx evaluationCtx) { ResourceFinderResult resourceResult = null; Set<EvaluationCtx> children = new HashSet<EvaluationCtx>(); AttributeValue resourceId = evaluationCtx.getResourceId(); int resourceScope = evaluationCtx.getResourceScope(); if(resourceId != null){ if(resourceScope == XACMLConstants.SCOPE_CHILDREN){ resourceResult = evaluationCtx.getPdpConfig().getResourceFinder(). findChildResources(resourceId, evaluationCtx); } else if(resourceScope == XACMLConstants.SCOPE_DESCENDANTS) { resourceResult = evaluationCtx.getPdpConfig().getResourceFinder(). findDescendantResources(resourceId, evaluationCtx); } else { logger.error("Unknown scope type: " ); //TODO } } else { logger.error("ResourceId Attribute is NULL: " ); // TODO } if(resourceResult == null || resourceResult.isEmpty()){ logger.error("Resource Finder result is NULL: " ); // TODO } else { for (AttributeValue resource : resourceResult.getResources()) { evaluationCtx.setResourceId(resource, attributesSet); children.add(evaluationCtx); } } return new MultipleCtxResult(children, null, false); } }
18,965
37.864754
130
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/ctx/xacml2/RequestCtx.java
/* * @(#)RequestCtx.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.ctx.xacml2; import org.wso2.balana.DOMHelper; import org.wso2.balana.ctx.Attribute; import org.wso2.balana.Indenter; import org.wso2.balana.ParsingException; import java.io.OutputStream; import java.io.PrintStream; import java.net.URI; import java.util.*; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.balana.XACMLConstants; import org.wso2.balana.ctx.*; import org.wso2.balana.xacml3.Attributes; /** * Represents a XACML2 request made to the PDP. This is the class that contains all the data used to start * a policy evaluation. * * @since 1.0 * @author Seth Proctor * @author Marco Barreno */ public class RequestCtx extends AbstractRequestCtx { /** * The optional, generic resource content */ private String resourceContent; // There must be at least one subject private Set<Subject> subjects = null; // There must be exactly one resource private Set resource = null; // There must be exactly one action private Set action = null; // There may be any number of environment attributes private Set environment = null; /** * Constructor that creates a <code>RequestCtx</code> from components. * */ public RequestCtx(Set<Attributes> attributesSet, Node documentRoot) { this(attributesSet, documentRoot, null); } /** * Constructor that creates a <code>RequestCtx</code> from components. * * @param documentRoot the root node of the DOM tree for this request * @param version xacml version of the request */ public RequestCtx(Set<Attributes> attributesSet, Node documentRoot, int version) { this(attributesSet, documentRoot, null); } /** * Constructor that creates a <code>RequestCtx</code> from components. * * @param resourceContent a text-encoded version of the content, suitable for including in the * RequestType, including the root <code>RequestContent</code> node */ public RequestCtx(Set<Attributes> attributesSet, String resourceContent) { this( attributesSet, null, resourceContent); } /** * Constructor that creates a <code>RequestCtx</code> from components. * * @param attributesSet * @param documentRoot the root node of the DOM tree for this request * @param resourceContent a text-encoded version of the content, suitable for including in the * RequestType, including the root <code>RequestContent</code> node * * @throws IllegalArgumentException if the inputs are not well formed */ public RequestCtx(Set<Attributes> attributesSet, Node documentRoot, String resourceContent) throws IllegalArgumentException { this.attributesSet = attributesSet; this.documentRoot = documentRoot; this.resourceContent = resourceContent; this.xacmlVersion = XACMLConstants.XACML_VERSION_2_0; } /** * * @param subjects * @param resource * @param action * @param environment * @throws IllegalArgumentException */ public RequestCtx(Set<Subject> subjects, Set<Attribute> resource, Set<Attribute> action, Set<Attribute> environment) throws IllegalArgumentException { this(null, null, subjects, resource, action, environment, null); } /** * Constructor that creates a <code>RequestCtx</code> from components. * * @param attributesSet * @param documentRoot the root node of the DOM tree for this request * @param resourceContent a text-encoded version of the content, suitable for including in the * RequestType, including the root <code>RequestContent</code> node * * @throws IllegalArgumentException if the inputs are not well formed */ public RequestCtx(Set<Attributes> attributesSet, Node documentRoot, Set<Subject> subjects, Set<Attribute> resource, Set<Attribute> action, Set<Attribute> environment, String resourceContent) throws IllegalArgumentException { this.attributesSet = attributesSet; this.documentRoot = documentRoot; this.subjects = subjects; this.resource = resource; this.action = action; this.environment = environment; this.resourceContent = resourceContent; this.xacmlVersion = XACMLConstants.XACML_VERSION_2_0; } /** * Create a new <code>RequestCtx</code> by parsing a node. This node should be created by * schema-verified parsing of an <code>XML</code> document. * * @param root the node to parse for the <code>RequestCtx</code> * * @return a new <code>RequestCtx</code> constructed by parsing * * @throws ParsingException if the DOM node is invalid */ public static RequestCtx getInstance(Node root) throws ParsingException { Set<Subject> newSubjects = new HashSet<Subject>(); Set<Attributes> attributesSet = new HashSet<Attributes>(); Node content = null; Set<Attribute> newResource = null; Set<Attribute> newAction = null; Set<Attribute> newEnvironment = null; // First check to be sure the node passed is indeed a Request node. String tagName = DOMHelper.getLocalName(root); if (!tagName.equals("Request")) { throw new ParsingException("Request cannot be constructed using " + "type: " + DOMHelper.getLocalName(root)); } // Now go through its child nodes, finding Subject, // Resource, Action, and Environment data NodeList children = root.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node node = children.item(i); String tag = DOMHelper.getLocalName(node); if (tag.equals("Subject")) { // see if there is a category Node catNode = node.getAttributes().getNamedItem("SubjectCategory"); URI category = null; if (catNode != null) { try { category = new URI(catNode.getNodeValue()); } catch (Exception e) { throw new ParsingException("Invalid Category URI", e); } } // now we get the attributes Set<Attribute> attributes = parseAttributes(node); // finally, add the list to the set of subject attributes newSubjects.add(new Subject(category, attributes)); // finally, add the list to the set of subject attributes attributesSet.add(new Attributes(category, null, attributes, null)); // make sure that there is at least one Subject if(newSubjects.size() < 1){ throw new ParsingException("Request must a contain subject"); } } else if (tag.equals("Resource")) { NodeList nodes = node.getChildNodes(); for (int j = 0; j < nodes.getLength(); j++) { Node child = nodes.item(j); if (DOMHelper.getLocalName(node).equals(XACMLConstants.RESOURCE_CONTENT)) { // only one value can be in an Attribute if (content != null){ throw new ParsingException("Too many resource content elements are defined."); } // now get the value content = node; } } // For now, this code doesn't parse the content, since it's // a set of anys with a set of anyAttributes, and therefore // no useful data can be gleaned from it anyway. The theory // here is that it's only useful in the instance doc, so // we won't bother parse it, but we may still want to go // back and provide some support at some point... newResource = parseAttributes(node); attributesSet.add(new Attributes(null, content, newResource, null)); } else if (tag.equals("Action")) { newAction = parseAttributes(node); attributesSet.add(new Attributes(null, content, newAction, null)); } else if (tag.equals("Environment")) { newEnvironment = parseAttributes(node); attributesSet.add(new Attributes(null, content, newEnvironment, null)); } } // if we didn't have an environment section, the only optional section // of the four, then create a new empty set for it if (newEnvironment == null){ newEnvironment = new HashSet<Attribute>(); attributesSet.add(new Attributes(null, content, newEnvironment, null)); } // Now create and return the RequestCtx from the information // gathered return new RequestCtx(attributesSet, root,newSubjects, newResource, newAction, newEnvironment, null); } /* * Helper method that parses a set of Attribute types. The Subject, Action and Environment * sections all look like this. */ private static Set<Attribute> parseAttributes(Node root) throws ParsingException { Set<Attribute> set = new HashSet<Attribute>(); // the Environment section is just a list of Attributes NodeList nodes = root.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (DOMHelper.getLocalName(node).equals("Attribute")) set.add(Attribute.getInstance(node, XACMLConstants.XACML_VERSION_2_0)); } return set; } /** * Returns a <code>Set</code> containing <code>Subject</code> objects. * * @return the request's subject attributes */ public Set getSubjects() { return subjects; } /** * Returns a <code>Set</code> containing <code>Attribute</code> objects. * * @return the request's resource attributes */ public Set getResource() { return resource; } /** * Returns a <code>Set</code> containing <code>Attribute</code> objects. * * @return the request's action attributes */ public Set getAction() { return action; } /** * Returns a <code>Set</code> containing <code>Attribute</code> objects. * * @return the request's environment attributes */ public Set getEnvironmentAttributes() { return environment; } /** * Returns the root DOM node of the document used to create this object, or null if this object * was created by hand (ie, not through the <code>getInstance</code> method) or if the root node * was not provided to the constructor. * * @return the root DOM node or null */ public Node getDocumentRoot() { return documentRoot; } /** * Encodes this <code>AbstractRequestCtx</code> into its XML representation and writes this encoding to the given * <code>OutputStream</code>. No indentation is used. * * @param output a stream into which the XML-encoded data is written */ public void encode(OutputStream output) { encode(output, new Indenter(0)); } /** * Encodes this <code>AbstractRequestCtx</code> into its XML representation and writes this encoding to the given * <code>OutputStream</code> with indentation. * * @param output a stream into which the XML-encoded data is written * @param indenter an object that creates indentation strings */ public void encode(OutputStream output, Indenter indenter) { // Make a PrintStream for a nicer printing interface PrintStream out = new PrintStream(output); // Prepare the indentation string String topIndent = indenter.makeString(); out.println(topIndent + "<Request xmlns=\"" + XACMLConstants.REQUEST_CONTEXT_2_0_IDENTIFIER + "\" >"); // go in one more for next-level elements... indenter.in(); String indent = indenter.makeString(); // ...and go in again for everything else indenter.in(); // first off, go through all subjects Iterator it = subjects.iterator(); while (it.hasNext()) { Subject subject = (Subject) (it.next()); out.print(indent + "<Subject SubjectCategory=\"" + subject.getCategory().toString() + "\""); Set subjectAttrs = subject.getAttributes(); if (subjectAttrs.size() == 0) { // there's nothing in this Subject, so just close the tag out.println("/>"); } else { // there's content, so fill it in out.println(">"); encodeAttributes(subjectAttrs, out, indenter); out.println(indent + "</Subject>"); } } // next do the resource if ((resource.size() != 0) || (resourceContent != null)) { out.println(indent + "<Resource>"); if (resourceContent != null) out.println(indenter.makeString() + "<ResourceContent>" + resourceContent + "</ResourceContent>"); encodeAttributes(resource, out, indenter); out.println(indent + "</Resource>"); } else { out.println(indent + "<Resource/>"); } // now the action if (action.size() != 0) { out.println(indent + "<Action>"); encodeAttributes(action, out, indenter); out.println(indent + "</Action>"); } else { out.println(indent + "<Action/>"); } // finally the environment, if there are any attrs if (environment.size() != 0) { out.println(indent + "<Environment>"); encodeAttributes(environment, out, indenter); out.println(indent + "</Environment>"); } // we're back to the top indenter.out(); indenter.out(); out.println(topIndent + "</Request>"); } /** * Private helper function to encode the attribute sets */ private void encodeAttributes(Set attributes, PrintStream out, Indenter indenter) { indenter.in(); Iterator it = attributes.iterator(); while (it.hasNext()) { Attribute attr = (Attribute) (it.next()); out.print(indenter.makeString() + attr.encode()); } indenter.out(); } }
16,696
36.690745
119
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/xacml3/AnyOfSelection.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.xacml3; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.balana.*; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.ctx.Status; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Represents AnyOfType in the XACML 3.0 policy schema.. */ public class AnyOfSelection { /** * */ private List<AllOfSelection> allOfSelections; private static final Log logger = LogFactory.getLog(AnyOfSelection.class); /** * Constructor that creates a new <code>AnyOfSelection</code> based on the given elements. * * @param allOfSelections a <code>List</code> of <code>AllOfSelection</code> elements */ public AnyOfSelection(List<AllOfSelection> allOfSelections) { if (allOfSelections == null) this.allOfSelections =new ArrayList<AllOfSelection>(); else this.allOfSelections = new ArrayList<AllOfSelection>(allOfSelections); } /** * creates a <code>AnyOfSelection</code> based on its DOM node. * * @param root the node to parse for the AnyOfSelection * @param metaData meta-date associated with the policy * * @return a new <code>AnyOfSelection</code> constructed by parsing * * @throws ParsingException if the DOM node is invalid */ public static AnyOfSelection getInstance(Node root, PolicyMetaData metaData) throws ParsingException { List<AllOfSelection> allOfSelections = new ArrayList<AllOfSelection>(); NodeList children = root.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if ("AllOf".equals(DOMHelper.getLocalName(child))) { allOfSelections.add(AllOfSelection.getInstance(child, metaData)); } } if(allOfSelections.isEmpty()){ throw new ParsingException("AnyOf must contain at least one AllOf"); } return new AnyOfSelection(allOfSelections); } /** * 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); } } public List<AllOfSelection> getAllOfSelections() { return allOfSelections; } /** * Encodes this <code>AnyOfSelection</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("<AnyOf>\n"); if(allOfSelections != null){ for(AllOfSelection allOfSelection : allOfSelections){ allOfSelection.encode(builder); } } builder.append("</AnyOf>\n"); } }
5,403
33.420382
101
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/xacml3/Obligation.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.xacml3; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.balana.DOMHelper; import org.wso2.balana.Indenter; import org.wso2.balana.ObligationResult; import org.wso2.balana.ParsingException; import org.wso2.balana.ctx.AttributeAssignment; import java.io.OutputStream; import java.io.PrintStream; import java.net.URI; import java.util.ArrayList; import java.util.List; /** * Represents the ObligationType XML type found in the context scheme in XACML 3.0 */ public class Obligation implements ObligationResult { /** * Identifier that uniquely identify the Obligation */ private URI obligationId; /** * <code>List</code> of <code>AttributeAssignment</code> that contains in * <code>Obligation</code> */ private List<AttributeAssignment> assignments; /** * Constructor that creates a new <code>Obligation</code> based on * the given elements. * * @param assignments <code>List</code> of <code>AttributeAssignment</code> * @param obligationId Identifier that uniquely identify the Obligation */ public Obligation(List<AttributeAssignment> assignments, URI obligationId) { this.assignments = assignments; this.obligationId = obligationId; } /** * creates a <code>Obligation</code> based on its DOM node. * * @param root the DOM root of the ObligationType XML type * @return an instance of an obligation * @throws ParsingException if the structure isn't valid */ public static Obligation getInstance(Node root) throws ParsingException { URI obligationId; List<AttributeAssignment> assignments = new ArrayList<AttributeAssignment>(); if (!DOMHelper.getLocalName(root).equals("Obligation")) { throw new ParsingException("Obligation object cannot be created " + "with root node of type: " + DOMHelper.getLocalName(root)); } NamedNodeMap nodeAttributes = root.getAttributes(); try { obligationId = new URI(nodeAttributes.getNamedItem("ObligationId").getNodeValue()); } catch (Exception e) { throw new ParsingException("Error parsing required ObligationId in " + "ObligationType", e); } NodeList children = root.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if ("AttributeAssignment".equals(DOMHelper.getLocalName(child))) { assignments.add(AttributeAssignment.getInstance(child)); } } return new Obligation(assignments, obligationId); } /** * Encodes this <code>Obligation</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("<Obligation ObligationId=\"").append(obligationId).append("\">"); if (assignments != null && assignments.size() > 0) { for (AttributeAssignment assignment : assignments) { assignment.encode(builder); } } builder.append("</Obligation>"); } /** * Returns the attribute assignment data in this obligation. The <code>List</code> contains * objects of type <code>Attribute</code> with only the correct attribute fields being used. * * @return the assignments */ public List<AttributeAssignment> getAssignments() { return assignments; } /** * Returns the obligation id of the obligation object * * @return the obligation Id */ public URI getObligationId() { return obligationId; } /** * Encodes this <code>Obligation</code> into its XML form * * @return <code>String</code> */ public String encode() { StringBuilder builder = new StringBuilder(); encode(builder); return builder.toString(); } }
4,807
30.424837
97
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/xacml3/ObligationExpression.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.xacml3; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.balana.*; import org.wso2.balana.ctx.AbstractResult; import org.wso2.balana.ctx.Attribute; import org.wso2.balana.ctx.AttributeAssignment; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.ctx.xacml2.Result; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * Represents ObligationExpressionType in the XACML 3.0 policy schema */ public class ObligationExpression extends AbstractObligation { /** * <code>List</code> of <code>AttributeAssignmentExpression</code> that contains in * <code>ObligationExpression</code> * */ private List<AttributeAssignmentExpression> expressions; /** * Constructor that creates a new <code>ObligationExpression</code> based on * the given elements. * * @param fulfillOn effect that will cause this obligation to be included in a response * @param expressions <code>List</code> of <code>AttributeAssignmentExpression</code> * @param obligationId Identifier that uniquely identify ObligationExpression element */ public ObligationExpression(int fulfillOn, List<AttributeAssignmentExpression> expressions, URI obligationId) { this.fulfillOn = fulfillOn; this.expressions = expressions; this.obligationId = obligationId; } /** * creates a <code>ObligationExpression</code> based on its DOM node. * * @param root root the node to parse for the ObligationExpression * @param metaData meta-date associated with the policy * @return a new <code>ObligationExpression</code> constructed by parsing * @throws ParsingException if the DOM node is invalid */ public static ObligationExpression getInstance(Node root, PolicyMetaData metaData) throws ParsingException { List<AttributeAssignmentExpression> expressions = new ArrayList<AttributeAssignmentExpression>(); URI obligationId; int fulfillOn; String effect; // First check that we're really parsing an Attribute if (!DOMHelper.getLocalName(root).equals("ObligationExpression")) { throw new ParsingException("ObligationExpression object cannot be created " + "with root node of type: " + DOMHelper.getLocalName(root)); } NamedNodeMap nodeAttributes = root.getAttributes(); try { obligationId = new URI(nodeAttributes.getNamedItem("ObligationId").getNodeValue()); } catch (Exception e) { throw new ParsingException("Error parsing required ObligationId in " + "ObligationExpressionType", e); } try { effect = nodeAttributes.getNamedItem("FulfillOn").getNodeValue(); } catch (Exception e) { throw new ParsingException("Error parsing required FulfillOn in " + "ObligationExpressionType", e); } if("Permit".equals(effect)){ fulfillOn = Result.DECISION_PERMIT; } else if("Deny".equals(effect)){ fulfillOn = Result.DECISION_DENY; } else { throw new ParsingException("Invalid FulfillOn : " + effect); } NodeList children = root.getChildNodes(); for(int i = 0; i < children.getLength(); i ++){ Node child = children.item(i); if("AttributeAssignmentExpression".equals(DOMHelper.getLocalName(child))){ expressions.add(AttributeAssignmentExpression.getInstance(child, metaData)); } } return new ObligationExpression(fulfillOn, expressions, obligationId); } @Override public ObligationResult evaluate(EvaluationCtx ctx) { List<AttributeAssignment> assignments = new ArrayList<AttributeAssignment>(); for(AttributeAssignmentExpression expression : expressions){ Set<AttributeAssignment> assignmentSet = expression.evaluate(ctx); if(assignmentSet != null && assignmentSet.size() > 0){ assignments.addAll(assignmentSet); } } return new Obligation(assignments, obligationId); } /** * 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>"); } }
5,679
36.124183
107
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/xacml3/Attributes.java
/* * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.xacml3; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.balana.*; import org.wso2.balana.ctx.Attribute; import org.wso2.balana.utils.Utils; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.net.URI; import java.util.HashSet; import java.util.Set; /** * Represents the AttributesType XML type found in the context schema. * TODO But here, not supporting the xml:id Identifier. Just use it as String attributes */ public class Attributes { /** * category of the Attributes element whether it is subject, action and etc */ private URI category; /** * content of the Attributes element that can be a XML data */ private Node content; /** * a <code>Set</code> of <code>Attribute</code> that contains in <code>Attributes</code> */ private Set<Attribute> attributes; /** * id of the Attribute element */ private String id; /** * Constructor that creates a new <code>Attributes</code> based on * the given elements. * @param category category of the Attributes element whether it is subject, action and etc * @param attributes a <code>Set</code> of <code>Attribute</code> * that contains in <code>Attributes</code> */ public Attributes(URI category,Set<Attribute> attributes) { this(category, null, attributes, null); } /** * Constructor that creates a new <code>Attributes</code> based on * the given elements. * @param category category of the Attributes element whether it is subject, action and etc * @param content content of the Attributes element that can be a XML data * @param attributes a <code>Set</code> of <code>Attribute</code> * that contains in <code>Attributes</code> * @param id id of the Attribute element */ public Attributes(URI category, Node content, Set<Attribute> attributes, String id) { this.category = category; this.content = content; this.attributes = attributes; this.id = id; } /** * * @param root * @return * @throws ParsingException */ public static Attributes getInstance(Node root) throws ParsingException { URI category ; Node content = null; String id = null; Set<Attribute> attributes = new HashSet<Attribute>(); // First check that we're really parsing an Attribute if (!DOMHelper.getLocalName(root).equals(XACMLConstants.ATTRIBUTES_ELEMENT)) { throw new ParsingException("Attributes object cannot be created " + "with root node of type: " + DOMHelper.getLocalName(root)); } NamedNodeMap attrs = root.getAttributes(); try { category = new URI(attrs.getNamedItem(XACMLConstants.ATTRIBUTES_CATEGORY).getNodeValue()); } catch (Exception e) { throw new ParsingException("Error parsing required attribute " + "AttributeId in AttributesType", e); } try { Node idNode = attrs.getNamedItem(XACMLConstants.ATTRIBUTES_ID); if(idNode != null){ id = idNode.getNodeValue(); } } catch (Exception e) { throw new ParsingException("Error parsing optional attributes in " + "AttributesType", e); } NodeList nodes = root.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (DOMHelper.getLocalName(node).equals(XACMLConstants.ATTRIBUTES_CONTENT)) { // only one value can be in an Attribute if (content != null){ throw new ParsingException("Too many content elements are defined."); } // now get the value content = node.getFirstChild(); } else if(DOMHelper.getLocalName(node).equals(XACMLConstants.ATTRIBUTE_ELEMENT)) { attributes.add(Attribute.getInstance(node, XACMLConstants.XACML_VERSION_3_0)); } } if(content != null){ // make the node appear to be a direct child of the Document try{ DocumentBuilderFactory dbf = Utils.getSecuredDocumentBuilderFactory(); DocumentBuilder builder = dbf.newDocumentBuilder(); dbf.setNamespaceAware(true); Document docRoot = builder.newDocument(); Node topRoot = docRoot.importNode(content, true); docRoot.appendChild(topRoot); content = docRoot.getDocumentElement(); } catch (Exception e){ // } } return new Attributes(category, content, attributes , id); } /** * Returns the category of this attributes * * @return the attribute 's category as <code>URI</code> */ public URI getCategory() { return category; } /** * Returns the content of this attributes, or null if no content was included * * @return the attribute 's content as <code>Node</code> or null */ public Node getContent() { return content; } /** * Returns list of attribute that contains in the attributes element * * @return list of <code>Attribute</code> */ public Set<Attribute> getAttributes() { return attributes; } /** * Returns the id of this attributes, or null if it was not included * * @return the attribute 's id as <code>String</code> or null */ public String getId() { return id; } /** * Encodes this <code>Attributes</code> into its XML form * * @return <code>String</code> */ public String encode() { StringBuilder builder = new StringBuilder(); encode(builder); return builder.toString(); } /** * Encodes this <code>Attributes</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("<Attributes Category=\"").append(category.toString()).append("\">"); for(Attribute attribute : attributes){ attribute.encode(builder); } if (content != null) { // TODO } builder.append("</Attributes>"); } // /** // * Encodes only the included attribute into its XML representation and writes this encoding to the given // * <code>OutputStream</code> with indentation. // * // * @param output a stream into which the XML-encoded data is written // * @param indenter an object that creates indentation strings // */ // public void encodeIncludeAttribute(OutputStream output, Indenter indenter) { // // String indent = indenter.makeString(); // PrintStream out = new PrintStream(output); // boolean atLestOneAttribute = false; // // for(Attribute attribute : attributes){ // if(attribute.isIncludeInResult()){ // if(!atLestOneAttribute){ // // if there is one included attribute, encode the attributes element // out.println(indent + "<Attributes Category=\"" + category.toString() + "\">"); // indenter.in(); // } // atLestOneAttribute = true; // attribute.encode(output, indenter); // } // } // // if(atLestOneAttribute){ // indenter.out(); // indenter.in(); // if (content != null) { // // TODO // } // // out.println(indent + "</Attributes>"); // } // } // /** // * Encodes this attribute into its XML representation and writes this encoding to the given // * <code>OutputStream</code> with indentation. // * // * @param output a stream into which the XML-encoded data is written // * @param indenter an object that creates indentation strings // */ // public void encodeWithIncludedAttributes(OutputStream output, Indenter indenter) { // // setup the formatting & outstream stuff // String indent = indenter.makeString(); // PrintStream out = new PrintStream(output); // // out.println(indent + "<Attributes Category=\"" + category.toString() + "\">"); // // indenter.in(); // // for(Attribute attribute : attributes){ // if(attribute.isIncludeInResult()){ // attribute.encode(output, indenter); // } // } // // indenter.out(); // // indenter.in(); // if (content != null) { // // TODO // } // // out.println(indent + "</Attributes>"); // } }
9,658
31.96587
110
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/xacml3/ObligationExpressions.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.xacml3; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.balana.DOMHelper; import org.wso2.balana.ParsingException; import org.wso2.balana.PolicyMetaData; import java.util.HashSet; import java.util.Set; /** * Represents ObligationExpressionType in the XACML 3.0 policy schema */ public class ObligationExpressions { /** * <code>Set</code> of <code>ObligationExpression</code> that contains in * <code>ObligationExpressions</code> */ Set<ObligationExpression> obligationExpressions; /** * Constructor that creates a new <code>ObligationExpressions</code> based on * the given elements. * * @param obligationExpressions <code>Set</code> of <code>ObligationExpression</code> */ public ObligationExpressions(Set<ObligationExpression> obligationExpressions) { this.obligationExpressions = obligationExpressions; } /** * creates a <code>ObligationExpressions</code> based on its DOM node. * * @param root root the node to parse for the ObligationExpressions * @param metaData meta-date associated with the policy * @return a new <code>ObligationExpressions</code> constructed by parsing * @throws ParsingException if the DOM node is invalid */ public static ObligationExpressions getInstance(Node root, PolicyMetaData metaData) throws ParsingException { Set<ObligationExpression> obligationExpressions = new HashSet<ObligationExpression>(); NodeList children = root.getChildNodes(); for(int i = 0; i < children.getLength(); i ++){ Node child = children.item(i); if("ObligationExpression".equals(DOMHelper.getLocalName(child))){ obligationExpressions.add(ObligationExpression.getInstance(child, metaData)); } } if(obligationExpressions.isEmpty()){ throw new ParsingException("ObligationExpressions must contain at least one " + "ObligationExpression"); } return new ObligationExpressions(obligationExpressions); } }
2,801
33.170732
113
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/xacml3/AttributeAssignmentExpression.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.xacml3; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.balana.DOMHelper; import org.wso2.balana.Indenter; import org.wso2.balana.ctx.AttributeAssignment; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.ParsingException; import org.wso2.balana.PolicyMetaData; import org.wso2.balana.attr.AttributeValue; import org.wso2.balana.attr.BagAttribute; import org.wso2.balana.cond.Evaluatable; import org.wso2.balana.cond.EvaluationResult; import org.wso2.balana.cond.Expression; import org.wso2.balana.cond.ExpressionHandler; import java.io.OutputStream; import java.net.URI; import java.util.*; /** * Represents AttributeAssignmentExpressionType in the XACML 3.0 policy schema.. */ public class AttributeAssignmentExpression { /** * attribute id of the AttributeAssignmentExpression element */ private URI attributeId; /** * category of the AttributeAssignmentExpression element whether it is subject, action and etc */ private URI category; /** * issuer of the AttributeAssignment */ private String issuer; /** * <code>Expression</code> that contains in <code>AttributeAssignmentExpression</code> */ private Expression expression; /** * Constructor that creates a new <code>AttributeAssignmentExpression</code> based on * the given elements. * @param attributeId attribute id of the AttributeAssignmentExpression element * @param category category of the AttributeAssignmentExpression element whether it is subject, action and etc * @param expression <code>Expression</code> that contains in <code>AttributeAssignmentExpression</code> * @param issuer issuer of the AttributeAssignment */ public AttributeAssignmentExpression(URI attributeId, URI category, Expression expression, String issuer) { this.attributeId = attributeId; this.category = category; this.expression = expression; this.issuer = issuer; } /** * creates a <code>AttributeAssignmentExpression</code> based on its DOM node. * * @param root root the node to parse for the AttributeAssignment * @param metaData meta-date associated with the policy * @return a new <code>AttributeAssignmentExpression</code> constructed by parsing * @throws ParsingException if the DOM node is invalid */ public static AttributeAssignmentExpression getInstance(Node root, PolicyMetaData metaData) throws ParsingException { URI attributeId; URI category = null; String issuer= null; Expression expression = null; if (!DOMHelper.getLocalName(root).equals("AttributeAssignmentExpression")) { throw new ParsingException("ObligationExpression object cannot be created " + "with root node of type: " + DOMHelper.getLocalName(root)); } NamedNodeMap nodeAttributes = root.getAttributes(); try { attributeId = new URI(nodeAttributes.getNamedItem("AttributeId").getNodeValue()); } catch (Exception e) { throw new ParsingException("Error parsing required AttributeId in " + "AttributeAssignmentExpressionType", e); } try { Node categoryNode = nodeAttributes.getNamedItem("Category"); if(categoryNode != null){ category = new URI(categoryNode.getNodeValue()); } Node issuerNode = nodeAttributes.getNamedItem("Issuer"); if(issuerNode != null){ issuer = issuerNode.getNodeValue(); } } catch (Exception e) { throw new ParsingException("Error parsing optional attributes in " + "AttributeAssignmentExpressionType", e); } NodeList children = root.getChildNodes(); // there can be only one expression TODO error when more than one expression for(int i = 0; i < children.getLength(); i ++){ if (children.item(i).getNodeType() == Node.ELEMENT_NODE) { expression = ExpressionHandler.parseExpression(children.item(i), metaData, null); break; } } if(expression == null){ throw new ParsingException("AttributeAssignmentExpression must contain at least one " + "Expression Type"); } return new AttributeAssignmentExpression(attributeId, category, expression, issuer); } /** * evaluates <code>Expression</code> element and create new <code>Set</code> of * <code>AttributeAssignment</code> * * @param ctx <code>EvaluationCtx</code> * @return <code>Set</code> of <code>AttributeAssignment</code> */ public Set<AttributeAssignment> evaluate(EvaluationCtx ctx) { Set<AttributeAssignment> values = new HashSet<AttributeAssignment>(); EvaluationResult result = ((Evaluatable)expression).evaluate(ctx); if(result == null || result.indeterminate()){ return null; } // TODO when indetermine policy also must be indetermine AttributeValue attributeValue = result.getAttributeValue(); if(attributeValue != null){ if(attributeValue.isBag()) { if(((BagAttribute)attributeValue).size() > 0 ){ Iterator iterator = ((BagAttribute)attributeValue).iterator(); while(iterator.hasNext()){ AttributeValue bagValue = (AttributeValue) iterator.next(); AttributeAssignment assignment = new AttributeAssignment(attributeId, bagValue.getType(), category, bagValue.encode(), issuer); values.add(assignment); } } else { return null; } } else { AttributeAssignment assignment = new AttributeAssignment(attributeId, attributeValue.getType(), category, attributeValue.encode(), issuer); values.add(assignment); } } return values; } /** * Encodes this <code>AttributeAssignmentExpression</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("<AttributeAssignmentExpression AttributeId=\"" + attributeId + "\""); if(category != null){ builder.append(" Category=\"" + category + "\""); } if(issuer != null){ builder.append(" Issuer=\"" + issuer + "\""); } builder.append(" >\n"); expression.encode(builder); builder.append("</AttributeAssignmentExpression>\n"); } }
7,833
35.95283
116
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/xacml3/MultiRequests.java
/* * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.xacml3; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.balana.DOMHelper; import org.wso2.balana.ParsingException; import org.wso2.balana.XACMLConstants; import java.net.URI; import java.util.HashSet; import java.util.Set; /** * Represents the MultiRequestsType XML type found in the context schema. */ public class MultiRequests { /** * <code>Set</code> of <code>RequestReference</code> that contains in <code>MultiRequests</code> */ private Set<RequestReference> requestReferences; /** * Constructor that creates a new <code>MultiRequests</code> based on * the given elements. * * @param requestReferences <code>Set</code> of <code>RequestReference</code> */ public MultiRequests(Set<RequestReference> requestReferences) { this.requestReferences = requestReferences; } /** * creates a <code>MultiRequests</code> based on its DOM node. * @param root root the node to parse for the AttributeAssignment * @return a new <code>MultiRequests</code> constructed by parsing * @throws ParsingException if the DOM node is invalid */ public static MultiRequests getInstance(Node root) throws ParsingException { Set<RequestReference> requestReferences = new HashSet<RequestReference>(); // First check that we're really parsing an MultiRequests if (!DOMHelper.getLocalName(root).equals("MultiRequests")) { throw new ParsingException("MultiRequests object cannot be created " + "with root node of type: " + DOMHelper.getLocalName(root)); } NodeList nodes = root.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if ("RequestReference".equals(DOMHelper.getLocalName(node))){ Set<AttributesReference> attributesReferences = new HashSet<AttributesReference>(); RequestReference requestReference = new RequestReference(); NodeList childNodes = node.getChildNodes(); for(int j = 0; j < childNodes.getLength(); j++){ Node childNode = childNodes.item(j); if("AttributesReference".equals(DOMHelper.getLocalName(childNode))){ AttributesReference attributesReference = new AttributesReference(); NamedNodeMap nodeAttributes = childNode.getAttributes(); try { String referenceId = nodeAttributes.getNamedItem("ReferenceId").getNodeValue(); attributesReference.setId(referenceId); attributesReferences.add(attributesReference); } catch (Exception e) { throw new ParsingException("Error parsing required ReferenceId in " + "AttributesReferenceType", e); } } } if(attributesReferences.isEmpty()){ throw new ParsingException("RequestReference must contain at least one " + "AttributesReferenceType"); } requestReference.setReferences(attributesReferences); requestReferences.add(requestReference); } } if(requestReferences.isEmpty()){ throw new ParsingException("MultiRequests must contain at least one RequestReferenceType"); } return new MultiRequests(requestReferences); } /** * returns <code>Set</code> of <code>RequestReference</code> * * @return <code>Set</code> of <code>RequestReference</code> */ public Set<RequestReference> getRequestReferences() { return requestReferences; } }
4,520
38.657895
107
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/xacml3/RequestDefaults.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.xacml3; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.balana.DOMHelper; import org.wso2.balana.Indenter; import java.io.OutputStream; import java.io.PrintStream; /** * Represents RequestDefaultsType XML type found in the context schema in XACML 3.0. */ public class RequestDefaults { /** * XPath Version */ private String xPathVersion; /** * Constructor that creates a new <code>RequestDefaults</code> based on * the given elements. * * @param xPathVersion XPath version as <code>String</code> */ public RequestDefaults(String xPathVersion) { this.xPathVersion = xPathVersion; } /** * creates a <code>RequestDefaults</code> based on its DOM node. * * @param root root the node to parse for the RequestDefaults * @return a new <code>RequestDefaults</code> constructed by parsing */ public static RequestDefaults getInstance(Node root){ String xPathVersion = null; NodeList nodes = root.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if ("XPathVersion".equals(DOMHelper.getLocalName(node))){ xPathVersion = node.getFirstChild().getNodeValue(); } } return new RequestDefaults(xPathVersion); } /** * returns XPath version * * @return XPath version as <code>String</code> */ public String getXPathVersion() { return xPathVersion; } /** * Encodes this <code>RequestDefaults</code> into its XML representation and writes this encoding to the given * <code>OutputStream</code> with no indentation. * * @param output a stream into which the XML-encoded data is written */ public void encode(OutputStream output) { encode(output, new Indenter(0)); } /** * Encodes this <code>RequestDefaults</code> into its XML representation and writes this encoding to the given * <code>OutputStream</code> with indentation. * * @param output a stream into which the XML-encoded data is written * @param indenter an object that creates indentation strings */ public void encode(OutputStream output, Indenter indenter) { String indent = indenter.makeString(); PrintStream out = new PrintStream(output); out.println(indent + "<RequestDefaults>"); if(xPathVersion != null){ indenter.in(); out.println(indent + "<XPathVersion>" + xPathVersion + "</XPathVersion>"); indenter.out(); } out.println(indent + "</RequestDefaults>"); } }
3,390
28.232759
114
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/xacml3/AttributesReference.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.xacml3; /** * Represents the AttributesReferenceType XML type found in the context schema. */ public class AttributesReference { private String id; public String getId() { return id; } public void setId(String id) { this.id = id; } }
958
25.638889
79
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/xacml3/Advice.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.xacml3; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.balana.DOMHelper; import org.wso2.balana.Indenter; import org.wso2.balana.ParsingException; import org.wso2.balana.ctx.AttributeAssignment; import java.io.OutputStream; import java.io.PrintStream; import java.net.URI; import java.util.ArrayList; import java.util.List; /** * Represents the AdviceType XML type in XACML. Advice are introduced with XACML 3 */ public class Advice { /** * The value of the advice identifier may be interpreted by the PEP. */ private URI adviceId; /** * Advice arguments as a <code>List</code> of <code>AttributeAssignment</code> * The values of the advice arguments may be interpreted by the PEP */ private List<AttributeAssignment> assignments; /** * Constructor that creates a new <code>Advice</code> based on * the given elements. * * @param adviceId Identifier that uniquely identify the Advice * @param assignments <code>List</code> of <code>AttributeAssignment</code> */ public Advice(URI adviceId, List<AttributeAssignment> assignments) { this.adviceId = adviceId; this.assignments = assignments; } /** * Encodes this <code>Advice</code> into its XML form * * @return <code>String</code> */ public String encode() { StringBuilder builder = new StringBuilder(); encode(builder); return builder.toString(); } /** * Creates a <code>Advice</code> based on its DOM node. * * @param root the DOM root of a AdviceType * @return an instance of an advice * @throws ParsingException if the structure isn't valid */ public static Advice getInstance(Node root) throws ParsingException { URI adviceId; List<AttributeAssignment> assignments = new ArrayList<AttributeAssignment>(); if (!DOMHelper.getLocalName(root).equals("Advice")) { throw new ParsingException("Advice object cannot be created " + "with root node of type: " + DOMHelper.getLocalName(root)); } NamedNodeMap nodeAttributes = root.getAttributes(); try { adviceId = new URI(nodeAttributes.getNamedItem("AdviceId").getNodeValue()); } catch (Exception e) { throw new ParsingException("Error parsing required AdviceId in " + "AdviceType", e); } NodeList children = root.getChildNodes(); for(int i = 0; i < children.getLength(); i ++){ Node child = children.item(i); if("AttributeAssignment".equals(DOMHelper.getLocalName(child))){ assignments.add(AttributeAssignment.getInstance(child)); } } return new Advice(adviceId, assignments); } public URI getAdviceId() { return adviceId; } public List<AttributeAssignment> getAssignments() { return assignments; } /** * Encodes this <code>Advice</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("<Advice AdviceId=\"").append(adviceId).append("\" >"); if(assignments != null && assignments.size() > 0){ for(AttributeAssignment assignment : assignments){ assignment.encode(builder); } } builder.append("</Advice>"); } }
4,312
29.807143
93
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/xacml3/AdviceExpression.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.xacml3; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.balana.*; import org.wso2.balana.ctx.AbstractResult; import org.wso2.balana.ctx.AttributeAssignment; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.ctx.xacml2.Result; import java.io.OutputStream; import java.io.PrintStream; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * Represents the AdviceExpressionType XML type in XACML. Advice are introduced with XACML 3 */ public class AdviceExpression { /** * The value of the advice identifier may be interpreted by the PEP. */ private URI adviceId; /** * The effect for which this advice must be provided to the PEP. */ private int appliesTo; /** * Advice arguments in the form of expressions; <code>AttributeAssignmentExpression</code> */ private List<AttributeAssignmentExpression> attributeAssignmentExpressions; /** * Constructor that takes all the data associated with an AdviceExpression * . * @param adviceId the advice's id * @param appliesTo the effect for which this advice must be provided * @param attributeAssignmentExpressions a <code>List</code> of <code>AttributeAssignmentExpression</code>s */ public AdviceExpression(URI adviceId, int appliesTo, List<AttributeAssignmentExpression> attributeAssignmentExpressions) { this.adviceId = adviceId; this.appliesTo = appliesTo; this.attributeAssignmentExpressions = attributeAssignmentExpressions; } /** * Creates an instance of <code>AdviceExpression</code> based on the DOM root node. * * @param root the DOM root of the AdviceExpressionType XML type * @param metaData policy meta data * @return an instance of an <code>AdviceExpression</code> * @throws ParsingException if the structure isn't valid */ public static AdviceExpression getInstance(Node root, PolicyMetaData metaData) throws ParsingException { URI adviceId; int appliesTo; String effect; List<AttributeAssignmentExpression> expressions = new ArrayList<AttributeAssignmentExpression>(); NamedNodeMap attrs = root.getAttributes(); try { adviceId = new URI(attrs.getNamedItem("AdviceId").getNodeValue()); } catch (Exception e) { throw new ParsingException("Error parsing required attribute AdviceId " + "in AdviceExpressionType", e); } try { effect = attrs.getNamedItem("AppliesTo").getNodeValue(); } catch (Exception e) { throw new ParsingException("Error parsing required attribute AppliesTo " + "in AdviceExpressionType", e); } if (effect.equals("Permit")) { appliesTo = AbstractResult.DECISION_PERMIT; } else if (effect.equals("Deny")) { appliesTo = AbstractResult.DECISION_DENY; } else { throw new ParsingException("Invalid Effect type: " + effect); } NodeList nodes = root.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (DOMHelper.getLocalName(node).equals("AttributeAssignmentExpression")) { try { AttributeAssignmentExpression expression = AttributeAssignmentExpression. getInstance(node, metaData); expressions.add(expression); } catch (Exception e) { throw new ParsingException("Error parsing attribute assignments " + "in AdviceExpressionType", e); } } } return new AdviceExpression(adviceId, appliesTo, expressions); } /** * returns whether this is applied for permit or deny * * @return permit/deny */ public int getAppliesTo() { return appliesTo; } /** * returns advice id * * @return advice id */ public URI getAdviceId() { return adviceId; } /** * return evaluation result of the advice expression * * @param ctx <code>EvaluationCtx</code> * @return result as <code>Advice</code> Object */ public Advice evaluate(EvaluationCtx ctx) { List<AttributeAssignment> assignments = new ArrayList<AttributeAssignment>(); for(AttributeAssignmentExpression expression : attributeAssignmentExpressions){ Set<AttributeAssignment> assignmentSet = expression.evaluate(ctx); if(assignmentSet != null && assignmentSet.size() > 0){ assignments.addAll(assignmentSet); } } return new Advice(adviceId, assignments); } /** * 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>"); } }
6,230
33.616667
111
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/xacml3/Target.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.xacml3; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.balana.*; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.ctx.Status; import java.io.OutputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Represents the TargetType XML type in XACML 3.0. This extends the AbstractTarget. * This also stores several other XML type: AnyOf */ public class Target extends AbstractTarget { /** * AnyOf sections of this target as list of <code>AnyOfSelection</code> */ List<AnyOfSelection> anyOfSelections; /** * Constructor that creates an XACML 3.0 <code>Target</code> * */ public Target() { this.anyOfSelections = new ArrayList<AnyOfSelection>(); } /** * Constructor that creates an XACML 3.0 <code>Target</code> from components. * * @param anyOfSelections List of <code>AnyOfSelection</code> objects that * representing the AnyOf sections of this target */ public Target(List<AnyOfSelection> anyOfSelections) { this.anyOfSelections = anyOfSelections; } /** * Creates a <code>Target</code> by parsing a node. * * @param root the node to parse for the <code>Target</code> * @param metaData the meta-data associated with the policy * @return new <code>Target</code> constructed by parsing * @throws org.wso2.balana.ParsingException if the DOM node is invalid */ public static Target getInstance(Node root, PolicyMetaData metaData) throws ParsingException { List<AnyOfSelection> anyOfSelections = new ArrayList<AnyOfSelection>(); NodeList children = root.getChildNodes(); for(int i = 0; i < children.getLength(); i++){ Node child = children.item(i); if("AnyOf".equals(DOMHelper.getLocalName(child))){ anyOfSelections.add(AnyOfSelection.getInstance(child, metaData)); } } return new Target(anyOfSelections); } /** * 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); } } public List<AnyOfSelection> getAnyOfSelections() { return anyOfSelections; } @Override public String encode() { StringBuilder sb = new StringBuilder(); encode(sb); return sb.toString(); } @Override public void encode(StringBuilder builder) { builder.append("<Target>\n"); if(anyOfSelections != null){ for(AnyOfSelection anyOfSelection : anyOfSelections){ anyOfSelection.encode(builder); } } builder.append("</Target>\n"); } }
4,434
30.453901
91
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/xacml3/RequestReference.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.xacml3; import java.util.Set; /** * Represents the RequestReferenceType XML type found in the context schema in XACML 3.0 */ public class RequestReference { private Set<AttributesReference> references; public Set<AttributesReference> getReferences() { return references; } public void setReferences(Set<AttributesReference> references) { this.references = references; } }
1,098
27.921053
89
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/xacml3/AllOfSelection.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.xacml3; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.balana.*; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.ctx.Status; import org.wso2.balana.TargetMatch; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Represents AllOfType in the XACML 3.0 policy schema. */ public class AllOfSelection { /** * List of SubjectMatch, ResourceMatch, ActionMatch, or EnvironmentMatch */ List<TargetMatch> matches; /** * Constructor that creates a <code>AllOfSelection</code> from components. * * @param matches a <code>List</code> of <code>TargetMatch</code> elements */ public AllOfSelection(List<TargetMatch> matches) { this.matches = matches; } /** * creates a new <code>AllOfSelection</code> by parsing DOM node. * * @param root DOM node * @param metaData policy meta data * @return <code>AllOfSelection</code> * @throws ParsingException throws, if the DOM node is invalid */ public static AllOfSelection getInstance(Node root, PolicyMetaData metaData) throws ParsingException { List<TargetMatch> targetMatches = new ArrayList<TargetMatch>(); NodeList children = root.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if ("Match".equals(DOMHelper.getLocalName(child))) { targetMatches.add(TargetMatch.getInstance(child, metaData)); } } if(targetMatches.isEmpty()){ throw new ParsingException("AllOf must contain at least one Match"); } return new AllOfSelection(targetMatches); } /** * * 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); } public List<TargetMatch> getMatches() { return matches; } /** * Encodes this <code>AnyOfSelection</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("<AllOf>\n"); if(matches != null){ for(TargetMatch match : matches){ match.encode(builder); } } builder.append("</AllOf>\n"); } }
4,325
29.680851
106
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/xacml3/MultipleCtxResult.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.xacml3; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.ctx.Status; import java.util.Set; /** * This is used in cases where a normal result is Set of contexts, but if an context couldn't * be created or any error is occurred during the creation, then a Status object needs to be * returned instead. */ public class MultipleCtxResult { /** * A ,<code>Set</code> of <code>EvaluationCtx</code> */ private Set<EvaluationCtx> evaluationCtxSet; /** * <code>Status<code> */ private Status status; /** * whether any indeterminate has occurred or not */ private boolean indeterminate; /** * Constructs a <code>MultipleCtxResult</code> object with required data * * @param evaluationCtxSet A ,<code>Set</code> of <code>EvaluationCtx</code> */ public MultipleCtxResult(Set<EvaluationCtx> evaluationCtxSet) { this(evaluationCtxSet, null, false); } /** * Constructs a <code>MultipleCtxResult</code> object with status error * * @param status <code>Status<code> */ public MultipleCtxResult(Status status) { this(null, status, true); } /** * Constructs a <code>MultipleCtxResult</code> object with required data * * @param evaluationCtxSet A ,<code>Set</code> of <code>EvaluationCtx</code> * @param status <code>Status<code> * @param indeterminate whether any indeterminate has occurred or not */ public MultipleCtxResult(Set<EvaluationCtx> evaluationCtxSet, Status status, boolean indeterminate) { this.evaluationCtxSet = evaluationCtxSet; this.status = status; this.indeterminate = indeterminate; } public Set<EvaluationCtx> getEvaluationCtxSet() { return evaluationCtxSet; } public Status getStatus() { if(indeterminate){ return status; } else { return null; } } public boolean isIndeterminate() { return indeterminate; } }
2,743
27.884211
105
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/xacml2/Obligation.java
/* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.balana.xacml2; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.balana.*; import org.wso2.balana.attr.AttributeFactory; import org.wso2.balana.attr.AttributeValue; import org.wso2.balana.ctx.Attribute; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.ctx.xacml2.Result; import java.io.OutputStream; import java.io.PrintStream; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Represents ObligationType in the XACML 2.0 policy schema. In XACML 2.0, this element represent both * in policy and result. Therefore this has extends the <code>AbstractObligation</code> and implements * the <code>ObligationResult</code> */ public class Obligation extends AbstractObligation implements ObligationResult { /** * A <code>List</code> of <code>Attribute</code> */ private List<Attribute> assignments; /** * Constructor that takes all the data associated with an obligation. The attribute assignment * list contains <code>Attribute</code> objects, but only the fields used by the * AttributeAssignmentType are used. * * @param obligationId the obligation's id * @param fulfillOn the effect denoting when to fulfill this obligation * @param assignments a <code>List</code> of <code>Attribute</code>s */ public Obligation(URI obligationId, int fulfillOn, List<Attribute> assignments) { this.obligationId = obligationId; this.fulfillOn = fulfillOn; this.assignments = Collections.unmodifiableList(new ArrayList<Attribute>(assignments)); } /** * Creates an instance of <code>Obligation</code> based on the DOM root node. * * @param root the DOM root of the ObligationType XML type * * @return an instance of an obligation * * @throws ParsingException if the structure isn't valid */ public static Obligation getInstance(Node root) throws ParsingException { URI id; int fulfillOn; String effect; List<Attribute> assignments = new ArrayList<Attribute>(); AttributeFactory attrFactory = Balana.getInstance().getAttributeFactory(); NamedNodeMap attrs = root.getAttributes(); try { id = new URI(attrs.getNamedItem("ObligationId").getNodeValue()); } catch (Exception e) { throw new ParsingException("Error parsing required attribute ObligationId", e); } try { effect = attrs.getNamedItem("FulfillOn").getNodeValue(); } catch (Exception e) { throw new ParsingException("Error parsing required attribute FulfillOn", e); } if (effect.equals("Permit")) { fulfillOn = Result.DECISION_PERMIT; } else if (effect.equals("Deny")) { fulfillOn = Result.DECISION_DENY; } else { throw new ParsingException("Invalid Effect type: " + effect); } NodeList nodes = root.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (DOMHelper.getLocalName(node).equals("AttributeAssignment")) { try { URI attrId = new URI(node.getAttributes().getNamedItem("AttributeId") .getNodeValue()); AttributeValue attrValue = attrFactory.createValue(node); assignments.add(new Attribute(attrId, null, null, attrValue, XACMLConstants.XACML_VERSION_2_0)); } catch (URISyntaxException use) { throw new ParsingException("Error parsing URI", use); } catch (UnknownIdentifierException uie) { throw new ParsingException(uie.getMessage(), uie); } catch (Exception e) { throw new ParsingException("Error parsing attribute assignments", e); } } } return new Obligation(id, fulfillOn, assignments); } @Override public ObligationResult evaluate(EvaluationCtx ctx) { return new Obligation(obligationId, fulfillOn, assignments); } /** * Returns the attribute assignment data in this obligation. The <code>List</code> contains * objects of type <code>Attribute</code> with only the correct attribute fields being used. * * @return the assignments */ public List<Attribute> getAssignments() { return assignments; } /** * Encodes this <code>Obligation</code> into its XML form * * @return <code>String</code> */ public String encode() { StringBuilder builder = new StringBuilder(); encode(builder); return builder.toString(); } /** * Encodes this <code>Obligation</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("<Obligation ObligationId=\"").append(obligationId.toString()). append("\" FulfillOn=\"").append(Result.DECISIONS[fulfillOn]).append("\">\n"); for (Attribute assignment : assignments) { builder.append("<AttributeAssignment AttributeId=\""). append(assignment.getId().toString()).append("\" DataType=\""). append(assignment.getType().toString()).append("\">"). append(assignment.getValue().encode()).append("</AttributeAssignment>\n"); } builder.append("</Obligation>"); } }
6,508
36.194286
102
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/xacml2/TargetMatchGroup.java
/* * @(#)TargetMatchGroup.java * * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.xacml2; import java.io.OutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.balana.*; import org.wso2.balana.ctx.EvaluationCtx; /** * This class contains a group of <code>TargetMatch</code> instances and represents the Subject, * Resource, Action, and Environment elements in an XACML Target. * * @since 2.0 * @author Seth Proctor */ public class TargetMatchGroup { // the list of matches private List<TargetMatch> matches; // the match type contained in this group private int matchType; // the logger we'll use for all messages private static final Log logger = LogFactory.getLog(TargetMatchGroup.class); /** * Constructor that creates a new <code>TargetMatchGroup</code> based on the given elements. * * @param matchElements a <code>List</code> of <code>TargetMatch</code> * @param matchType the match type as defined in <code>TargetMatch</code> */ public TargetMatchGroup(List<TargetMatch> matchElements, int matchType) { if (matchElements == null) matches = Collections.unmodifiableList(new ArrayList<TargetMatch>()); else matches = Collections.unmodifiableList(new ArrayList<TargetMatch>(matchElements)); this.matchType = matchType; } /** * Creates a <code>Target</code> based on its DOM node. * * @param root the node to parse for the target group * @param matchType the type of the match * @param metaData meta-date associated with the policy * * @return a new <code>TargetMatchGroup</code> constructed by parsing * * @throws org.wso2.balana.ParsingException if the DOM node is invalid */ public static TargetMatchGroup getInstance(Node root, int matchType, PolicyMetaData metaData) throws ParsingException { List<TargetMatch> matches = new ArrayList<TargetMatch>(); NodeList children = root.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); String name = DOMHelper.getLocalName(child); String matchName = TargetMatch.NAMES[matchType] + "Match"; if (name.equals(matchName)) { matches.add(TargetMatch.getInstance(child, matchType, metaData)); } } return new TargetMatchGroup(matches, matchType); } /** * Determines whether this <code>TargetMatchGroup</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) { MatchResult result = null; if (matches.isEmpty()) { // nothing in target, return match return new MatchResult(MatchResult.MATCH); } for (TargetMatch targetMatch : matches) { result = targetMatch.match(context); if (result.getResult() != MatchResult.MATCH) break; } return result; } /** * Encodes this <code>TargetMatchGroup</code> into its XML form * * @return <code>String</code> */ public String encode() { StringBuilder builder = new StringBuilder(); encode(builder); return builder.toString(); } /** * Encodes this <code>TargetMatchGroup</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) { String name = TargetMatch.NAMES[matchType]; builder.append("<").append(name).append(">\n"); for (TargetMatch targetMatch : matches) { targetMatch.encode(builder); } builder.append("</").append(name).append(">\n"); } }
6,063
34.255814
103
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/xacml2/TargetSection.java
/* * @(#)TargetSection.java * * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.xacml2; import org.wso2.balana.*; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.ctx.Status; import java.io.OutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * This is a container class for instances of <code>TargetMatchGroup</code> * and represents the Subjects, Resources, Actions, and Environments * sections of an XACML Target. This section may apply to any request. * * @since 2.0 * @author Seth Proctor */ public class TargetSection { // the list of match groups private List<TargetMatchGroup> matchGroups; // the match type contained in this group private int matchType; // the version of XACML used by the containing Target private int xacmlVersion; /** * Constructor that takes a group and a version. If the group is * null or empty, then this represents a section that matches any request. * * @param matchGroups a possibly null <code>List</code> of * <code>TargetMatchGroup</code>s * @param matchType the type as defined in <code>TargetMatch</code> * @param xacmlVersion the version XACML being used */ public TargetSection(List<TargetMatchGroup> matchGroups, int matchType, int xacmlVersion) { if (matchGroups == null) this.matchGroups = Collections.unmodifiableList(new ArrayList<TargetMatchGroup>()); else this.matchGroups = Collections. unmodifiableList(new ArrayList<TargetMatchGroup>(matchGroups)); this.matchType = matchType; this.xacmlVersion = xacmlVersion; } /** * Creates a <code>Target</code> by parsing a node. * * @param root the node to parse for the <code>Target</code> * @param matchType the type as defined in <code>TargetMatch</code> * @param metaData the meta-data from the enclosing policy * * @return a new <code>Target</code> constructed by parsing * * @throws org.wso2.balana.ParsingException if the DOM node is invalid */ public static TargetSection getInstance(Node root, int matchType, PolicyMetaData metaData) throws ParsingException { List<TargetMatchGroup> groups = new ArrayList<TargetMatchGroup>(); NodeList children = root.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); String name = DOMHelper.getLocalName(child); String typeName = TargetMatch.NAMES[matchType]; if (name.equals(typeName)) { groups.add(TargetMatchGroup.getInstance(child, matchType, metaData)); } else if (name.equals("Any" + typeName)) { // in a schema-valid policy, the Any element will always be // the only element, so if we find this we stop break; } } // at this point the list is non-empty (it has specific groups to // match) or is empty (it applies to any request using the 1.x or // 2.0 syntax) return new TargetSection(groups, matchType, metaData.getXACMLVersion()); } /** * Returns the <code>TargetMatchGroup</code>s contained in this group. * * @return a <code>List</code> of <code>TargetMatchGroup</code>s */ public List getMatchGroups() { return matchGroups; } /** * Returns whether this section matches any request. * * @return true if this section matches any request, false otherwise */ public boolean matchesAny() { return matchGroups.isEmpty(); } /** * 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); } /** * Encodes this <code>TargetSection</code> into its XML form * * @return <code>String</code> */ public String encode() { StringBuilder builder = new StringBuilder(); encode(builder); return builder.toString(); } /** * Encodes this <code>TargetSection</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) { String name = TargetMatch.NAMES[matchType]; // figure out if this section applies to any request if (matchGroups.isEmpty()) { // this applies to any, so now we need to encode it based on // what version of XACML we're using...in 2.0, we encode an Any // by simply omitting the element, so we'll only actually include // something if this is a 1.x policy if (xacmlVersion == XACMLConstants.XACML_VERSION_1_0) { builder.append("<").append(name).append("s>\n"); builder.append("<Any").append(name).append("/>\n"); builder.append("</").append(name).append("s>\n"); } } else { // this has specific rules, so we can now encode them builder.append("<").append(name).append("s>\n"); for (TargetMatchGroup group : matchGroups) { group.encode(builder); } builder.append("</").append(name).append("s>\n"); } } }
9,212
37.3875
100
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/xacml2/Target.java
/* * @(#)Target.java * * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.xacml2; import java.io.OutputStream; import java.io.PrintStream; import java.util.HashSet; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.balana.*; import org.wso2.balana.ctx.EvaluationCtx; /** * Represents the TargetType XML type in XACML. This also stores several other XML types: Subjects, * Resources, Actions, and Environments (in XACML 2.0 and later). The target is used to quickly * identify whether the parent element (a policy set, policy, or rule) is applicable to a given * request. * * @since 1.0 * @author Seth Proctor */ public class Target extends AbstractTarget { // the four sections of a Target private TargetSection subjectsSection; private TargetSection resourcesSection; private TargetSection actionsSection; private TargetSection environmentsSection; // the version of XACML of the policy containing this target private int xacmlVersion; // the logger we'll use for all messages private static final Log logger = LogFactory.getLog(Target.class); /** * Constructor that creates an XACML 1.x <code>Target</code> from components. Each of the * sections must be non-null, but they may match any request. Because this is only used for 1.x * Targets, there is no Environments section. * * @param subjectsSection a <code>TargetSection</code> representing the Subjects section of this * target * @param resourcesSection a <code>TargetSection</code> representing the Resources section of * this target * @param actionsSection a <code>TargetSection</code> representing the Actions section of this * target */ public Target(TargetSection subjectsSection, TargetSection resourcesSection, TargetSection actionsSection) { if ((subjectsSection == null) || (resourcesSection == null) || (actionsSection == null)) throw new ProcessingException("All sections of a Target must " + "be non-null"); this.subjectsSection = subjectsSection; this.resourcesSection = resourcesSection; this.actionsSection = actionsSection; this.environmentsSection = new TargetSection(null, TargetMatch.ENVIRONMENT, XACMLConstants.XACML_VERSION_1_0); this.xacmlVersion = XACMLConstants.XACML_VERSION_1_0; } /** * Constructor that creates an XACML 2.0 <code>Target</code> from components. Each of the * sections must be non-null, but they may match any request. * * @param subjectsSection a <code>TargetSection</code> representing the Subjects section of this * target * @param resourcesSection a <code>TargetSection</code> representing the Resources section of * this target * @param actionsSection a <code>TargetSection</code> representing the Actions section of this * target * @param environmentsSection a <code>TargetSection</code> representing the Environments section * of this target */ public Target(TargetSection subjectsSection, TargetSection resourcesSection, TargetSection actionsSection, TargetSection environmentsSection) { if ((subjectsSection == null) || (resourcesSection == null) || (actionsSection == null) || (environmentsSection == null)) throw new ProcessingException("All sections of a Target must " + "be non-null"); this.subjectsSection = subjectsSection; this.resourcesSection = resourcesSection; this.actionsSection = actionsSection; this.environmentsSection = environmentsSection; this.xacmlVersion = XACMLConstants.XACML_VERSION_2_0; } /** * Creates a <code>Target</code> by parsing a node. * * @deprecated As of 2.0 you should avoid using this method and should instead use the version * that takes a <code>PolicyMetaData</code> instance. This method will only work for * XACML 1.x policies. * * @param root the node to parse for the <code>Target</code> * @param xpathVersion the XPath version to use in any selectors, or null if this is unspecified * (ie, not supplied in the defaults section of the policy) * * @return a new <code>Target</code> constructed by parsing * * @throws ParsingException if the DOM node is invalid */ public static Target getInstance(Node root, String xpathVersion) throws ParsingException { return getInstance(root, new PolicyMetaData(XACMLConstants.XACML_1_0_IDENTIFIER, xpathVersion)); } /** * Creates a <code>Target</code> by parsing a node. * * @param root the node to parse for the <code>Target</code> * @param metaData * @return a new <code>Target</code> constructed by parsing * * @throws ParsingException if the DOM node is invalid */ public static Target getInstance(Node root, PolicyMetaData metaData) throws ParsingException { TargetSection subjects = null; TargetSection resources = null; TargetSection actions = null; TargetSection environments = null; int version = metaData.getXACMLVersion(); NodeList children = root.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); String name = DOMHelper.getLocalName(child); if (name.equals("Subjects")) { subjects = TargetSection.getInstance(child, TargetMatch.SUBJECT, metaData); } else if (name.equals("Resources")) { resources = TargetSection.getInstance(child, TargetMatch.RESOURCE, metaData); } else if (name.equals("Actions")) { actions = TargetSection.getInstance(child, TargetMatch.ACTION, metaData); } else if (name.equals("Environments")) { environments = TargetSection.getInstance(child, TargetMatch.ENVIRONMENT, metaData); } } // starting in 2.0 an any-matching section is represented by a // missing element, and in 1.x there were no Environments elements, // so these need to get turned into non-null arguments if (subjects == null) subjects = new TargetSection(null, TargetMatch.SUBJECT, version); if (resources == null) resources = new TargetSection(null, TargetMatch.RESOURCE, version); if (actions == null) actions = new TargetSection(null, TargetMatch.ACTION, version); if (version == XACMLConstants.XACML_VERSION_2_0) { if (environments == null) environments = new TargetSection(null, TargetMatch.ENVIRONMENT, version); return new Target(subjects, resources, actions, environments); } else { return new Target(subjects, resources, actions); } } /** * Returns the Subjects section of this Target. * * @return a <code>TargetSection</code> representing the Subjects */ public TargetSection getSubjectsSection() { return subjectsSection; } /** * Returns the Resources section of this Target. * * @return a <code>TargetSection</code> representing the Resources */ public TargetSection getResourcesSection() { return resourcesSection; } /** * Returns the Actions section of this Target. * * @return a <code>TargetSection</code> representing the Actions */ public TargetSection getActionsSection() { return actionsSection; } /** * Returns the Environments section of this Target. Note that if this is an XACML 1.x policy, * then the section will always match anything, since XACML 1.x doesn't support matching on the * Environment. * * @return a <code>TargetSection</code> representing the Environments */ public TargetSection getEnvironmentsSection() { return environmentsSection; } /** * Returns whether or not this <code>Target</code> matches any request. * * @return true if this Target matches any request, false otherwise */ public boolean matchesAny() { return subjectsSection.matchesAny() && resourcesSection.matchesAny() && actionsSection.matchesAny() && environmentsSection.matchesAny(); } /** * 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) { MatchResult result = null; String subjectPolicyValue; String resourcePolicyValue; String actionPolicyValue; String envPolicyValue; // before matching, see if this target matches any request if (matchesAny()) return new MatchResult(MatchResult.MATCH); // first, try matching the Subjects section result = subjectsSection.match(context); if (result.getResult() != MatchResult.MATCH) { if (logger.isDebugEnabled()) { logger.debug("failed to match Subjects section of Target"); } return result; } subjectPolicyValue = result.getPolicyValue(); // now try matching the Resources section result = resourcesSection.match(context); if (result.getResult() != MatchResult.MATCH) { if (logger.isDebugEnabled()) { logger.debug("failed to match Resources section of Target"); } return result; } resourcePolicyValue = result.getPolicyValue(); // next, look at the Actions section result = actionsSection.match(context); if (result.getResult() != MatchResult.MATCH) { if (logger.isDebugEnabled()) { logger.debug("failed to match Actions section of Target"); } return result; } actionPolicyValue = result.getPolicyValue(); // finally, match the Environments section result = environmentsSection.match(context); if (result.getResult() != MatchResult.MATCH) { if (logger.isDebugEnabled()) { logger.debug("failed to match Environments section of Target"); } return result; } envPolicyValue = result.getPolicyValue(); result.setActionPolicyValue(actionPolicyValue); result.setSubjectPolicyValue(subjectPolicyValue); result.setEnvPolicyValue(envPolicyValue); result.setResourcePolicyValue(resourcePolicyValue); // if we got here, then everything matched return result; } /** * Encodes this <code>Target</code> into its XML form * * @return <code>String</code> */ public String encode() { StringBuilder builder = new StringBuilder(); encode(builder); return builder.toString(); } /** * Encodes this <code>Target</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) { // see if this Target matches anything boolean matchesAny = (subjectsSection.matchesAny() && resourcesSection.matchesAny() && actionsSection.matchesAny() && environmentsSection.matchesAny()); if (matchesAny && (xacmlVersion == XACMLConstants.XACML_VERSION_2_0)) { // in 2.0, if all the sections match any request, then the Target // element is empty and should be encoded simply as en empty tag builder.append("<Target/>\n"); } else { builder.append("<Target>\n"); subjectsSection.encode(builder); resourcesSection.encode(builder); actionsSection.encode(builder); // we should only do this if we're a 2.0 policy if (xacmlVersion == XACMLConstants.XACML_VERSION_2_0){ environmentsSection.encode(builder); } builder.append("</Target>\n"); } } }
14,399
39
100
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/BagFunction.java
/* * @(#)BagFunction.java * * Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.cond; import org.wso2.balana.attr.AnyURIAttribute; import org.wso2.balana.attr.Base64BinaryAttribute; import org.wso2.balana.attr.BooleanAttribute; import org.wso2.balana.attr.DateAttribute; import org.wso2.balana.attr.DateTimeAttribute; import org.wso2.balana.attr.DayTimeDurationAttribute; import org.wso2.balana.attr.DNSNameAttribute; import org.wso2.balana.attr.DoubleAttribute; import org.wso2.balana.attr.HexBinaryAttribute; import org.wso2.balana.attr.IntegerAttribute; import org.wso2.balana.attr.IPAddressAttribute; import org.wso2.balana.attr.RFC822NameAttribute; import org.wso2.balana.attr.StringAttribute; import org.wso2.balana.attr.TimeAttribute; import org.wso2.balana.attr.X500NameAttribute; import org.wso2.balana.attr.YearMonthDurationAttribute; import java.util.HashSet; import java.util.Set; /** * Represents all of the Bag functions, though the actual implementations are in two sub-classes * specific to the condition and general bag functions. * * @since 1.0 * @author Seth Proctor */ public abstract class BagFunction extends FunctionBase { /** * Base name for the type-one-and-only funtions. To get the standard identifier for a given * type, use <code>FunctionBase.FUNCTION_NS</code> + the datatype's base name (e.g., * <code>string</code>) + </code>NAME_BASE_ONE_AND_ONLY</code>. */ public static final String NAME_BASE_ONE_AND_ONLY = "-one-and-only"; /** * Base name for the type-bag-size funtions. To get the standard identifier for a given type, * use <code>FunctionBase.FUNCTION_NS</code> + the datatype's base name (e.g., * <code>string</code>) + </code>NAME_BASE_BAG_SIZE</code>. */ public static final String NAME_BASE_BAG_SIZE = "-bag-size"; /** * Base name for the type-is-in. To get the standard identifier for a given type, use * <code>FunctionBase.FUNCTION_NS</code> + the datatype's base name (e.g., <code>string</code>) * + </code>NAME_BASE_IS_IN</code>. */ public static final String NAME_BASE_IS_IN = "-is-in"; /** * Base name for the type-bag funtions. To get the standard identifier for a given type, use * <code>FunctionBase.FUNCTION_NS</code> + the datatype's base name (e.g., <code>string</code>) * + </code>NAME_BASE_BAG</code>. */ public static final String NAME_BASE_BAG = "-bag"; // bag parameter info for the functions that accept multiple args private static final boolean bagParams[] = { false, true }; /** * A complete list of all the XACML 1.x datatypes supported by the Bag functions */ protected static String baseTypes[] = { StringAttribute.identifier, BooleanAttribute.identifier, IntegerAttribute.identifier, DoubleAttribute.identifier, DateAttribute.identifier, DateTimeAttribute.identifier, TimeAttribute.identifier, AnyURIAttribute.identifier, HexBinaryAttribute.identifier, Base64BinaryAttribute.identifier, DayTimeDurationAttribute.identifier, YearMonthDurationAttribute.identifier, X500NameAttribute.identifier, RFC822NameAttribute.identifier }; /** * A complete list of all the XACML 2.0 datatypes newly supported by the Bag functions */ protected static String baseTypes2[] = { IPAddressAttribute.identifier, DNSNameAttribute.identifier }; /** * A complete list of all the 1.x XACML datatypes supported by the Bag functions, using the * "simple" form of the names (eg, string instead of http://www.w3.org/2001/XMLSchema#string) */ protected static String simpleTypes[] = { "string", "boolean", "integer", "double", "date", "dateTime", "time", "anyURI", "hexBinary", "base64Binary", "dayTimeDuration", "yearMonthDuration", "x500Name", "rfc822Name" }; /** * A complete list of all the 2.0 XACML datatypes newly supported by the Bag functions, using * the "simple" form of the names (eg, string instead of * http://www.w3.org/2001/XMLSchema#string) */ protected static String simpleTypes2[] = { "ipAddress", "dnsName" }; /** * Returns a new <code>BagFunction</code> that provides the type-one-and-only functionality over * the given attribute type. This should be used to create new function instances for any new * attribute types, and the resulting object should be put into the <code>FunctionFactory</code> * (instances already exist in the factory for the standard attribute types). * * @param functionName the name to use for the function * @param argumentType the type to operate on * * @return a new <code>BagFunction</code> */ public static BagFunction getOneAndOnlyInstance(String functionName, String argumentType) { return new GeneralBagFunction(functionName, argumentType, NAME_BASE_ONE_AND_ONLY); } /** * Returns a new <code>BagFunction</code> that provides the type-bag-size functionality over the * given attribute type. This should be used to create new function instances for any new * attribute types, and the resulting object should be put into the <code>FunctionFactory</code> * (instances already exist in the factory for the standard attribute types). * * @param functionName the name to use for the function * @param argumentType the type to operate on * * @return a new <code>BagFunction</code> */ public static BagFunction getBagSizeInstance(String functionName, String argumentType) { return new GeneralBagFunction(functionName, argumentType, NAME_BASE_BAG_SIZE); } /** * Returns a new <code>BagFunction</code> that provides the type-is-in functionality over the * given attribute type. This should be used to create new function instances for any new * attribute types, and the resulting object should be put into the <code>FunctionFactory</code> * (instances already exist in the factory for the standard attribute types). * * @param functionName the name to use for the function * @param argumentType the type to operate on * * @return a new <code>BagFunction</code> */ public static BagFunction getIsInInstance(String functionName, String argumentType) { return new ConditionBagFunction(functionName, argumentType); } /** * Returns a new <code>BagFunction</code> that provides the type-bag functionality over the * given attribute type. This should be used to create new function instances for any new * attribute types, and the resulting object should be put into the <code>FunctionFactory</code> * (instances already exist in the factory for the standard attribute types). * * @param functionName the name to use for the function * @param argumentType the type to operate on * * @return a new <code>BagFunction</code> */ public static BagFunction getBagInstance(String functionName, String argumentType) { return new GeneralBagFunction(functionName, argumentType, NAME_BASE_BAG); } /** * Protected constuctor used by the general and condition subclasses to create a non-boolean * function with parameters of the same datatype. If you need to create a new * <code>BagFunction</code> instance you should either use one of the <code>getInstance</code> * methods or construct one of the sub-classes directly. * * @param functionName the identitifer for the function * @param functionId an optional, internal numeric identifier * @param paramType the datatype this function accepts * @param paramIsBag whether the parameters are bags * @param numParams number of parameters allowed or -1 for any number * @param returnType the datatype this function returns * @param returnsBag whether this function returns bags */ protected BagFunction(String functionName, int functionId, String paramType, boolean paramIsBag, int numParams, String returnType, boolean returnsBag) { super(functionName, functionId, paramType, paramIsBag, numParams, returnType, returnsBag); } /** * Protected constuctor used by the general and condition subclasses to create a boolean * function with parameters of different datatypes. If you need to create a new * <code>BagFunction</code> instance you should either use one of the <code>getInstance</code> * methods or construct one of the sub-classes directly. * * @param functionName the identitifer for the function * @param functionId an optional, internal numeric identifier * @param paramTypes the datatype of each parameter */ protected BagFunction(String functionName, int functionId, String[] paramTypes) { super(functionName, functionId, paramTypes, bagParams, BooleanAttribute.identifier, false); } /** * Returns a <code>Set</code> containing all the function identifiers supported by this class. * * @return a <code>Set</code> of <code>String</code>s */ public static Set getSupportedIdentifiers() { Set set = new HashSet(); set.addAll(ConditionBagFunction.getSupportedIdentifiers()); set.addAll(GeneralBagFunction.getSupportedIdentifiers()); return set; } }
11,191
46.02521
100
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/EvaluationResult.java
/* * @(#)EvaluationResult.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.cond; import org.wso2.balana.MatchResult; import org.wso2.balana.attr.AttributeValue; import org.wso2.balana.attr.BooleanAttribute; import org.wso2.balana.ctx.Status; /** * This is used in cases where a normal result is some AttributeValue, but if an attribute couldn't * be resolved (or some other problem occurred), then a Status object needs to be returned instead. * This is used instead of throwing an exception for performance, but mainly because failure to * resolve an attribute is not an error case for the code, merely for the evaluation, and represents * normal operation. Separate exception types will be added later to represent errors in pdp * operation. * * @since 1.0 * @author Seth Proctor */ public class EvaluationResult { // private boolean wasInd; private AttributeValue value; private Status status; private MatchResult matchResult; /** * Single instances of EvaluationResults with false and true BooleanAttributes in them. This * avoids the need to create new objects when performing boolean operations, which we do a lot * of. */ private static EvaluationResult falseBooleanResult; private static EvaluationResult trueBooleanResult; /** * Constructor that creates an <code>EvaluationResult</code> containing a single * <code>AttributeValue</code> * * @param value the attribute value */ public EvaluationResult(AttributeValue value) { wasInd = false; this.value = value; this.status = null; } /** * Constructor that creates an <code>EvaluationResult</code> of Indeterminate, including Status * data. * * @param status the error information */ public EvaluationResult(Status status) { wasInd = true; this.value = null; this.status = status; } public MatchResult getMatchResult() { return matchResult; } public void setMatchResult(MatchResult matchResult) { this.matchResult = matchResult; } /** * Returns true if the result was indeterminate * * @return true if there was an error */ public boolean indeterminate() { return wasInd; } /** * Returns the attribute value, or null if there was an error * * @return the attribute value or null */ public AttributeValue getAttributeValue() { return value; } /** * Returns the status if there was an error, or null it no error occurred * * @return the status or null */ public Status getStatus() { return status; } /** * Returns an <code>EvaluationResult</code> that represents the boolean value provided. * * @param value a boolean representing the desired value * @return an <code>EvaluationResult</code> representing the appropriate value */ public static EvaluationResult getInstance(boolean value) { if (value) return getTrueInstance(); else return getFalseInstance(); } /** * Returns an <code>EvaluationResult</code> that represents a false value. * * @return an <code>EvaluationResult</code> representing a false value */ public static EvaluationResult getFalseInstance() { if (falseBooleanResult == null) { falseBooleanResult = new EvaluationResult(BooleanAttribute.getFalseInstance()); } return falseBooleanResult; } /** * Returns an <code>EvaluationResult</code> that represents a true value. * * @return an <code>EvaluationResult</code> representing a true value */ public static EvaluationResult getTrueInstance() { if (trueBooleanResult == null) { trueBooleanResult = new EvaluationResult(BooleanAttribute.getTrueInstance()); } return trueBooleanResult; } }
5,763
33.309524
100
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/Condition.java
/* * @(#)Condition.java * * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.cond; import org.wso2.balana.*; import org.wso2.balana.attr.BooleanAttribute; import java.io.OutputStream; import java.io.PrintStream; import java.net.URI; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.wso2.balana.ctx.EvaluationCtx; /** * Represents the XACML ConditionType type. It contains exactly one child expression that is boolean * and returns a single value. This class was added in XACML 2.0 * * @since 2.0 * @author Seth Proctor */ public class Condition implements Evaluatable { // a local Boolean URI that is used as the return type private static URI booleanIdentifier; // regardless of version, this contains the Condition's children private List<Expression> children; // regardless of version, this is an expression that can be evaluated // directly private Expression expression; // the condition function, which is only used if this is a 1.x condition private Function function; // flags whether this is XACML 1.x or 2.0 private boolean isVersionOne; // initialize the boolean identifier static { try { booleanIdentifier = new URI(BooleanAttribute.identifier); } catch (Exception e) { // we ignore this, since it cannot happen, but it should be // flagged in case something changes to trip this case booleanIdentifier = null; } } /** * Constructs a <code>Condition</code> as used in XACML 1.x. * * @param function the <code>Function</code> to use in evaluating the elements in the Condition * @param expressions the contents of the Condition which will be the parameters to the function, each * of which is an <code>Expression</code> * * @throws IllegalArgumentException if the input expressions don't match the signature of the * function or if the function is invalid for use in a Condition */ public Condition(Function function, List expressions) throws IllegalArgumentException { isVersionOne = true; // check that the function is valid for a Condition checkExpression(function); // turn the parameters into an Apply for simplicity expression = new Apply(function, expressions); // keep track of the function and the children this.function = function; children = ((Apply) expression).getChildren(); } /** * Constructs a <code>Condition</code> as used in XACML 2.0. * * @param expression the child <code>Expression</code> * * @throws IllegalArgumentException if the expression is not boolean or returns a bag */ public Condition(Expression expression) throws IllegalArgumentException { isVersionOne = false; // check that the function is valid for a Condition checkExpression(expression); // store the expression this.expression = expression; // there is no function in a 2.0 Condition function = null; // store the expression as the child List list = new ArrayList(); list.add(this.expression); children = Collections.unmodifiableList(list); } /** * Private helper for the constructors that checks if a given expression is valid for the root * of a Condition */ private void checkExpression(Expression xpr) { // make sure it's a boolean expression... if (!xpr.getType().equals(booleanIdentifier)) throw new IllegalArgumentException("A Condition must return a " + "boolean...cannot create " + "with " + xpr.getType()); // ...and that it never returns a bag if (xpr.returnsBag()) throw new IllegalArgumentException("A Condition must not return " + "a Bag"); } /** * Returns an instance of <code>Condition</code> based on the given DOM root. * * @param root the DOM root of a ConditionType XML type * @param metaData the meta-data associated with the containing policy * @param manager <code>VariableManager</code> used to connect references and definitions while * parsing * * @throws ParsingException if this is not a valid ConditionType */ public static Condition getInstance(Node root, PolicyMetaData metaData, VariableManager manager) throws ParsingException { if (metaData.getXACMLVersion() < XACMLConstants.XACML_VERSION_2_0) { Apply cond = Apply.getConditionInstance(root, metaData.getXPathIdentifier(), manager); return new Condition(cond.getFunction(), cond.getChildren()); } else { Expression xpr = null; NodeList nodes = root.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { if (nodes.item(i).getNodeType() == Node.ELEMENT_NODE) { xpr = ExpressionHandler.parseExpression(nodes.item(i), metaData, manager); break; } } return new Condition(xpr); } } /** * Returns the <code>Function</code> used by this <code>Condition</code> if this is a 1.x * condition, or null if this is a 2.0 condition. * * @return a <code>Function</code> or null */ public Function getFunction() { return function; } /** * Returns the <code>List</code> of children for this <code>Condition</code>. The * <code>List</code> contains <code>Expression</code>s. The list is unmodifiable. * * @return a <code>List</code> of <code>Expression</code>s */ public List getChildren() { return children; } /** * Returns the type of attribute that this object will return on a call to <code>evaluate</code> * . This is always a boolean, since that's all that a Condition is allowed to return. * * @return the boolean type */ public URI getType() { return booleanIdentifier; } /** * Returns whether or not this <code>Condition</code> will return a bag of values on evaluation. * This always returns false, since a Condition isn't allowed to return a bag. * * @return false */ public boolean returnsBag() { return false; } /** * Returns whether or not this <code>Condition</code> will return a bag of values on evaluation. * This always returns false, since a Condition isn't allowed to return a bag. * * @deprecated As of 2.0, you should use the <code>returnsBag</code> method from the * super-interface <code>Expression</code>. * * @return false */ public boolean evaluatesToBag() { return false; } /** * Evaluates the <code>Condition</code> by evaluating its child <code>Expression</code>. * * @param context the representation of the request * * @return the result of trying to evaluate this condition object */ public EvaluationResult evaluate(EvaluationCtx context) { // Note that it's technically possible for this expression to // be something like a Function, which isn't Evaluatable. It // wouldn't make sense to have this, but it is possible. Because // it makes no sense, however, it's unlcear exactly what the // error should be, so raising the ClassCastException here seems // as good an approach as any for now... return ((Evaluatable) expression).evaluate(context); } /** * Encodes this <code>Condition</code> into its XML form * * @return <code>String</code> */ public String encode() { StringBuilder builder = new StringBuilder(); encode(builder); return builder.toString(); } /** * Encodes this <code>Condition</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) { if (isVersionOne) { builder.append("<Condition FunctionId=\"").append(function.getIdentifier()).append("\">\n"); for (Expression aChildren : children) { aChildren.encode(builder); } } else { builder.append("<Condition>\n"); expression.encode(builder); } builder.append("</Condition>\n"); } }
10,473
34.993127
106
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/VariableReference.java
/* * @(#)VariableReference.java * * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.cond; import org.w3c.dom.Node; import org.wso2.balana.ParsingException; import org.wso2.balana.PolicyMetaData; import org.wso2.balana.ProcessingException; import org.wso2.balana.ctx.EvaluationCtx; import java.net.URI; import java.util.Collections; import java.util.List; /** * This class supports the VariableReferenceType type introuced in XACML 2.0. It allows an * expression to reference a variable definition. If there is no such definition then the Policy is * invalid. A reference can be included anywwhere in an expression where the referenced expression * would be valid. * * @author Seth Proctor * @since 2.0 */ public class VariableReference implements Expression, Evaluatable { // the identifier used to resolve the reference private String variableId; // the actual definition we refernce, if it's known private VariableDefinition definition = null; // a manager for resolving references, if it's been provided private VariableManager manager = null; /** * Simple constructor that takes only the identifier. This is provided for tools that want to * build policies only for the sake of encoding or displaying them. This constructor will not * create a reference that can be followed to its associated definition, so it cannot be used in * evaluation. * * @param variableId the reference identifier */ public VariableReference(String variableId) { this.variableId = variableId; } /** * Constructor that takes the definition referenced by this class. If you're building policies * programatically, this is typically the form you use. It does make the connection from * reference to definition, so this will result in an evaluatable reference. * * @param definition the definition this class references */ public VariableReference(VariableDefinition definition) { this.variableId = definition.getVariableId(); this.definition = definition; } /** * Constructor that takes the reference identifier and a manager. This is typically only used by * parsing code, since the manager is used to handle out-of-order definitions and circular * references. * * @param variableId the reference identifier * @param manager a <code>VariableManager</code> used to handle the dependencies between * references and definitions during parsing */ public VariableReference(String variableId, VariableManager manager) { this.variableId = variableId; this.manager = manager; } /** * Returns a new instance of the <code>VariableReference</code> class based on a DOM node. The * node must be the root of an XML VariableReferenceType. * * @param root the DOM root of a VariableReferenceType XML type * @param metaData the meta-data associated with the containing policy * @param manager the <code>VariableManager</code> used to connect this reference to its * definition * @throws ParsingException if the VariableReferenceType is invalid */ public static VariableReference getInstance(Node root, PolicyMetaData metaData, VariableManager manager) throws ParsingException { // pretty easy, since there's just an attribute... String variableId = root.getAttributes().getNamedItem("VariableId").getNodeValue(); // ...but we keep the manager since after this we'll probably get // asked for our type, etc., and the manager will also be used to // resolve the actual definition return new VariableReference(variableId, manager); } /** * Returns the reference identifier. * * @return the reference's identifier */ public String getVariableId() { return variableId; } /** * Returns the <code>VariableDefinition</code> referenced by this class, or null if the * definition cannot be resolved. * * @return the referenced definition or null */ public VariableDefinition getReferencedDefinition() { // if this was created with a concrete definition, then that's what // we return, otherwise we query the manager (if we have one) if (definition != null) { return definition; } else if (manager != null) { return manager.getDefinition(variableId); } // if the simple constructor was used, then we have nothing return null; } /** * Evaluates the referenced expression using the given context, and either returns an error or a * resulting value. If this doesn't reference an evaluatable expression (eg, a single Function) * then this will throw an exception. * * @param context the representation of the request * @return the result of evaluation */ public EvaluationResult evaluate(EvaluationCtx context) { Expression xpr = getReferencedDefinition().getExpression(); // Note that it's technically possible for this expression to // be something like a Function, which isn't Evaluatable. It // wouldn't make sense to have this, but it is possible. Because // it makes no sense, however, it's unlcear exactly what the // error should be, so raising the ClassCastException here seems // as good an approach as any for now... return ((Evaluatable) xpr).evaluate(context); } /** * Returns the type of the referenced expression. * * @return the attribute return type of the referenced expression * @throws ProcessingException if the type couldn't be resolved */ public URI getType() { // if we have a concrete definition, then ask it for the type, // otherwise query the manager using the getVariableType method, // since this handles type-checking for definitions that haven't // been parsed yet if (definition != null) { return definition.getExpression().getType(); } else { if (manager != null) return manager.getVariableType(variableId); } throw new ProcessingException("couldn't resolve the type"); } /** * Tells whether evaluation will return a bag or a single value. * * @return true if evaluation will return a bag, false otherwise * @throws ProcessingException if the return type couldn't be resolved */ public boolean returnsBag() { // see comment in getType() if (definition != null) { return getReferencedDefinition().getExpression().returnsBag(); } else { if (manager != null) return manager.returnsBag(variableId); } throw new ProcessingException("couldn't resolve the return type"); } /** * Tells whether evaluation will return a bag or a single value. * * @return true if evaluation will return a bag, false otherwise * @throws ProcessingException if the return type couldn't be resolved * @deprecated As of 2.0, you should use the <code>returnsBag</code> method from the * super-interface <code>Expression</code>. */ public boolean evaluatesToBag() { return returnsBag(); } /** * Always returns an empty list since references never have children in the policy tree. Note * that the referenced definition may still have children, so tools may want to treat these as * children of this reference, but must take care since circular references could create a tree * of infinite depth. * * @return an empty <code>List</code> */ public List getChildren() { return Collections.EMPTY_LIST; } /** * Encodes this <code>VariableReference</code> into its XML form * * @return <code>String</code> */ public String encode() { StringBuilder builder = new StringBuilder(); encode(builder); return builder.toString(); } /** * Encodes this <code>VariableReference</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("<VariableReference VariableId=\"").append(variableId).append("\"/>\n"); } }
10,342
38.780769
104
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/EqualFunction.java
/* * @(#)EqualFunction.java * * Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.cond; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.XACMLConstants; import org.wso2.balana.attr.AnyURIAttribute; import org.wso2.balana.attr.AttributeValue; import org.wso2.balana.attr.Base64BinaryAttribute; import org.wso2.balana.attr.BooleanAttribute; import org.wso2.balana.attr.DateAttribute; import org.wso2.balana.attr.DateTimeAttribute; import org.wso2.balana.attr.DayTimeDurationAttribute; import org.wso2.balana.attr.DNSNameAttribute; import org.wso2.balana.attr.DoubleAttribute; import org.wso2.balana.attr.HexBinaryAttribute; import org.wso2.balana.attr.IntegerAttribute; import org.wso2.balana.attr.IPAddressAttribute; import org.wso2.balana.attr.RFC822NameAttribute; import org.wso2.balana.attr.StringAttribute; import org.wso2.balana.attr.TimeAttribute; import org.wso2.balana.attr.YearMonthDurationAttribute; import org.wso2.balana.attr.X500NameAttribute; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Set; /** * A class that implements all the *-equal functions. It takes two operands of the appropriate type * and returns a <code>BooleanAttribute</code> indicating whether both of the operands are equal. If * either of the operands is indeterminate, an indeterminate result is returned. * * @since 1.0 * @author Steve Hanna * @author Seth Proctor */ public class EqualFunction extends FunctionBase { /** * Standard identifier for the string-equal function. */ public static final String NAME_STRING_EQUAL = FUNCTION_NS + "string-equal"; /** * Standard identifier for the boolean-equal function. */ public static final String NAME_BOOLEAN_EQUAL = FUNCTION_NS + "boolean-equal"; /** * Standard identifier for the integer-equal function. */ public static final String NAME_INTEGER_EQUAL = FUNCTION_NS + "integer-equal"; /** * Standard identifier for the double-equal function. */ public static final String NAME_DOUBLE_EQUAL = FUNCTION_NS + "double-equal"; /** * Standard identifier for the date-equal function. */ public static final String NAME_DATE_EQUAL = FUNCTION_NS + "date-equal"; /** * Standard identifier for the time-equal function. */ public static final String NAME_TIME_EQUAL = FUNCTION_NS + "time-equal"; /** * Standard identifier for the dateTime-equal function. */ public static final String NAME_DATETIME_EQUAL = FUNCTION_NS + "dateTime-equal"; /** * Standard identifier for the dayTimeDuration-equal function. */ public static final String NAME_DAYTIME_DURATION_EQUAL = FUNCTION_NS + "dayTimeDuration-equal"; /** * Standard identifier for the yearMonthDuration-equal function. */ public static final String NAME_YEARMONTH_DURATION_EQUAL = FUNCTION_NS + "yearMonthDuration-equal"; /** * Standard identifier for the anyURI-equal function. */ public static final String NAME_ANYURI_EQUAL = FUNCTION_NS + "anyURI-equal"; /** * Standard identifier for the x500Name-equal function. */ public static final String NAME_X500NAME_EQUAL = FUNCTION_NS + "x500Name-equal"; /** * Standard identifier for the rfc822Name-equal function. */ public static final String NAME_RFC822NAME_EQUAL = FUNCTION_NS + "rfc822Name-equal"; /** * Standard identifier for the hexBinary-equal function. */ public static final String NAME_HEXBINARY_EQUAL = FUNCTION_NS + "hexBinary-equal"; /** * Standard identifier for the base64Binary-equal function. */ public static final String NAME_BASE64BINARY_EQUAL = FUNCTION_NS + "base64Binary-equal"; /** * Standard identifier for the ipAddress-equal function. */ public static final String NAME_IPADDRESS_EQUAL = FUNCTION_NS_2 + "ipAddress-equal"; /** * Standard identifier for the dnsName-equal function. */ public static final String NAME_DNSNAME_EQUAL = FUNCTION_NS_2 + "dnsName-equal"; /** * Standard identifier for the sting equal with ignore case */ public static final String NAME_EQUAL_CASE_IGNORE = FUNCTION_NS_3 + "string-equal-ignore-case"; // internal identifiers for each of the supported functions private static final int ID_EQUAL_CASE_IGNORE = 1; // private mapping of standard functions to their argument types private static HashMap typeMap; /** * Static initializer sets up a map of standard function names to their associated datatypes */ static { typeMap = new HashMap(); typeMap.put(NAME_STRING_EQUAL, StringAttribute.identifier); typeMap.put(NAME_BOOLEAN_EQUAL, BooleanAttribute.identifier); typeMap.put(NAME_INTEGER_EQUAL, IntegerAttribute.identifier); typeMap.put(NAME_DOUBLE_EQUAL, DoubleAttribute.identifier); typeMap.put(NAME_DATE_EQUAL, DateAttribute.identifier); typeMap.put(NAME_TIME_EQUAL, TimeAttribute.identifier); typeMap.put(NAME_DATETIME_EQUAL, DateTimeAttribute.identifier); typeMap.put(NAME_DAYTIME_DURATION_EQUAL, DayTimeDurationAttribute.identifier); typeMap.put(NAME_YEARMONTH_DURATION_EQUAL, YearMonthDurationAttribute.identifier); typeMap.put(NAME_ANYURI_EQUAL, AnyURIAttribute.identifier); typeMap.put(NAME_X500NAME_EQUAL, X500NameAttribute.identifier); typeMap.put(NAME_RFC822NAME_EQUAL, RFC822NameAttribute.identifier); typeMap.put(NAME_HEXBINARY_EQUAL, HexBinaryAttribute.identifier); typeMap.put(NAME_BASE64BINARY_EQUAL, Base64BinaryAttribute.identifier); typeMap.put(NAME_IPADDRESS_EQUAL, IPAddressAttribute.identifier); typeMap.put(NAME_DNSNAME_EQUAL, DNSNameAttribute.identifier); typeMap.put(NAME_EQUAL_CASE_IGNORE, StringAttribute.identifier); } /** * Returns an <code>EqualFunction</code> that provides the type-equal functionality over the * given attribute type. This should be used to create new function instances for any new * attribute types, and the resulting object should be put into the <code>FunctionFactory</code> * (instances for the standard types are pre-installed in the standard factory). * <p> * Note that this method has the same affect as invoking the constructor with the same * parameters. This method is provided as a convenience, and for symmetry with the bag and set * functions. * * @param functionName the name to use for the function * @param argumentType the type to operate on * * @return a new <code>EqualFunction</code> */ public static EqualFunction getEqualInstance(String functionName, String argumentType) { return new EqualFunction(functionName, argumentType); } /** * Creates a new <code>EqualFunction</code> object that supports one of the standard type-equal * functions. If you need to create an instance for a custom type, use the * <code>getEqualInstance</code> method or the alternate constructor. * * @param functionName the standard XACML name of the function to be handled by this object, * including the full namespace * * @throws IllegalArgumentException if the function isn't standard */ public EqualFunction(String functionName) { this(functionName, getArgumentType(functionName)); } /** * Creates a new <code>EqualFunction</code> object. * * @param functionName the standard XACML name of the function to be handled by this object, * including the full namespace * @param argumentType the standard XACML name for the type of the arguments, inlcuding the full * namespace */ public EqualFunction(String functionName, String argumentType) { super(functionName, getId(functionName), argumentType, false, 2, BooleanAttribute.identifier, false); } /** * Private helper that returns the type used for the given standard type-equal function. */ private static String getArgumentType(String functionName) { String datatype = (String) (typeMap.get(functionName)); if (datatype == null) throw new IllegalArgumentException("not a standard function: " + functionName); return datatype; } /** * Private helper that returns the internal identifier used for the given standard function. * * @param functionName function name * @return function id */ private static int getId(String functionName) { if (functionName.equals(NAME_EQUAL_CASE_IGNORE)){ return ID_EQUAL_CASE_IGNORE; } else { return 0; } } /** * Returns a <code>Set</code> containing all the function identifiers supported by this class. * * @return a <code>Set</code> of <code>String</code>s */ public static Set getSupportedIdentifiers() { return Collections.unmodifiableSet(typeMap.keySet()); } /** * Evaluate the function, using the specified parameters. * * @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the * arguments passed to the function * @param context an <code>EvaluationCtx</code> so that the <code>Evaluatable</code> objects can * be evaluated * @return an <code>EvaluationResult</code> representing the function's result */ 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; if (argValues[1] instanceof StringAttribute && XACMLConstants.ANY.equals(((StringAttribute) argValues[1]).getValue())) { return EvaluationResult.getInstance(true); } // Now that we have real values, perform the equals operation if(getFunctionId() == ID_EQUAL_CASE_IGNORE){ return EvaluationResult.getInstance(argValues[0].encode().toLowerCase(). equals(argValues[1].encode().toLowerCase())); } else { return EvaluationResult.getInstance(argValues[0].equals(argValues[1])); } } }
12,273
39.242623
109
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/HigherOrderFunction.java
/* * @(#)HigherOrderFunction.java * * Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.cond; import org.wso2.balana.ctx.EvaluationCtx; import org.wso2.balana.Indenter; import org.wso2.balana.attr.AttributeValue; import org.wso2.balana.attr.BagAttribute; import org.wso2.balana.attr.BooleanAttribute; import java.io.OutputStream; import java.io.PrintStream; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; /** * Represents all of the higher order bag functions, except map, which has its own class due to the * issues with its return type. Unlike the other functions that are designed to work over any types * (the type-* functions) these functions don't use specific names to describe what type they * operate over, so you don't need to install new instances for any new datatypes you define. * * @since 1.0 * @author Seth Proctor */ public class HigherOrderFunction implements Function { /** * Standard identifier for the any-of function. */ public static final String NAME_ANY_OF = FunctionBase.FUNCTION_NS + "any-of"; /** * Standard identifier for the all-of function. */ public static final String NAME_ALL_OF = FunctionBase.FUNCTION_NS + "all-of"; /** * Standard identifier for the any-of-any function. */ public static final String NAME_ANY_OF_ANY = FunctionBase.FUNCTION_NS + "any-of-any"; /** * Standard identifier for the all-of-any function. */ public static final String NAME_ALL_OF_ANY = FunctionBase.FUNCTION_NS + "all-of-any"; /** * Standard identifier for the any-of-all function. */ public static final String NAME_ANY_OF_ALL = FunctionBase.FUNCTION_NS + "any-of-all"; /** * Standard identifier for the all-of-all function. */ public static final String NAME_ALL_OF_ALL = FunctionBase.FUNCTION_NS + "all-of-all"; // internal identifiers for each of the supported functions private static final int ID_ANY_OF = 0; private static final int ID_ALL_OF = 1; private static final int ID_ANY_OF_ANY = 2; private static final int ID_ALL_OF_ANY = 3; private static final int ID_ANY_OF_ALL = 4; private static final int ID_ALL_OF_ALL = 5; // internal mapping of names to ids private static HashMap<String, Integer> idMap; // the internal identifier for each function private int functionId; // the real identifier for each function private URI identifier; // should the second argument (the first arg passed to the sub-function) // be a bag private boolean secondIsBag; // the stuff used to make sure that we have a valid return type or a // known error, just like in the attribute classes private static URI returnTypeURI; private static RuntimeException earlyException; // try to create the return type URI, and also setup the id map static { try { returnTypeURI = new URI(BooleanAttribute.identifier); } catch (Exception e) { earlyException = new IllegalArgumentException(); earlyException.initCause(e); } idMap = new HashMap<String, Integer>(); idMap.put(NAME_ANY_OF, Integer.valueOf(ID_ANY_OF)); idMap.put(NAME_ALL_OF, Integer.valueOf(ID_ALL_OF)); idMap.put(NAME_ANY_OF_ANY, Integer.valueOf(ID_ANY_OF_ANY)); idMap.put(NAME_ALL_OF_ANY, Integer.valueOf(ID_ALL_OF_ANY)); idMap.put(NAME_ANY_OF_ALL, Integer.valueOf(ID_ANY_OF_ALL)); idMap.put(NAME_ALL_OF_ALL, Integer.valueOf(ID_ALL_OF_ALL)); }; /** * Creates a new instance of the given function. * * @param functionName the function to create * * @throws IllegalArgumentException if the function is unknown */ public HigherOrderFunction(String functionName) { // try to get the function's identifier Integer i = (Integer) (idMap.get(functionName)); if (i == null) throw new IllegalArgumentException("unknown function: " + functionName); functionId = i.intValue(); // setup the URI form of this function's idenitity try { identifier = new URI(functionName); } catch (URISyntaxException use) { throw new IllegalArgumentException("invalid URI"); } // see if the second arg is a bag if ((functionId != ID_ANY_OF) && (functionId != ID_ALL_OF)) secondIsBag = true; else secondIsBag = false; } /** * Returns a <code>Set</code> containing all the function identifiers supported by this class. * * @return a <code>Set</code> of <code>String</code>s */ public static Set getSupportedIdentifiers() { return Collections.unmodifiableSet(idMap.keySet()); } /** * Returns the full identifier of this function, as known by the factories. * * @return the function's identifier */ public URI getIdentifier() { return identifier; } /** * Returns the same value as <code>getReturnType</code>. This is here to support the * <code>Expression</code> interface. * * @return the return type */ public URI getType() { return getReturnType(); } /** * Returns the type of attribute value that will be returned by this function. * * @return the return type */ public URI getReturnType() { if (earlyException != null) throw earlyException; return returnTypeURI; } /** * Returns whether or not this function will actually return a bag of values. * * @return true if the function returns a bag of values, otherwise false */ public boolean returnsBag() { return false; } /** * Evaluates the function, using the specified parameters. * * @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the * arguments passed to the function * @param context an <code>EvaluationCtx</code> so that the <code>Evaluatable</code> objects can * be evaluated * @return an <code>EvaluationResult</code> representing the function's result */ public EvaluationResult evaluate(List inputs, EvaluationCtx context) { Iterator iterator = inputs.iterator(); // get the first arg, which is the function Expression xpr = (Expression) (iterator.next()); Function function = null; if (xpr instanceof Function) { function = (Function) xpr; } else { function = (Function) (((VariableReference) xpr).getReferencedDefinition() .getExpression()); } // get the two inputs, and if anything is INDETERMINATE, then we // stop right away AttributeValue[] args = new AttributeValue[2]; Evaluatable eval = (Evaluatable) (iterator.next()); EvaluationResult result = eval.evaluate(context); if (result.indeterminate()) return result; args[0] = (AttributeValue) (result.getAttributeValue()); eval = (Evaluatable) (iterator.next()); result = eval.evaluate(context); if (result.indeterminate()) return result; args[1] = (AttributeValue) (result.getAttributeValue()); // now we're ready to do the evaluation result = null; switch (functionId) { case ID_ANY_OF: { // param: boolean-function, single value, bag of same type // return: boolean // using the function, iterate through the bag, and if one // of the bag elements matches the single value, return // true, otherwise return false result = any(args[0], (BagAttribute) (args[1]), function, context, false); break; } case ID_ALL_OF: { // param: boolean-function, single value, bag of same type // return: boolean // using the function, iterate through the bag, and if all // of the bag elements match the single value, return // true, otherwise return false result = all(args[0], (BagAttribute) (args[1]), function, context); break; } case ID_ANY_OF_ANY: { // param: boolean-function, bag, bag of same type // return: boolean // apply the function to every combination of a single value from // the first bag and a single value from the second bag, and if // any evaluation is true return true, otherwise return false result = new EvaluationResult(BooleanAttribute.getInstance(false)); Iterator it = ((BagAttribute) args[0]).iterator(); BagAttribute bag = (BagAttribute) (args[1]); while (it.hasNext()) { AttributeValue value = (AttributeValue) (it.next()); result = any(value, bag, function, context, false); if (result.indeterminate()) return result; if (((BooleanAttribute) (result.getAttributeValue())).getValue()) break; } break; } case ID_ALL_OF_ANY: { // param: boolean-function, bag, bag of same type // return: boolean // iterate through the first bag, and if for each of those values // one of the values in the second bag matches then return true, // otherwise return false result = allOfAny((BagAttribute) (args[1]), (BagAttribute) (args[0]), function, context); break; } case ID_ANY_OF_ALL: { // param: boolean-function, bag, bag of same type // return: boolean // iterate through the second bag, and if for each of those values // one of the values in the first bag matches then return true, // otherwise return false result = anyOfAll((BagAttribute) (args[0]), (BagAttribute) (args[1]), function, context); break; } case ID_ALL_OF_ALL: { // param: boolean-function, bag, bag of same type // return: boolean // iterate through the first bag, and for each of those values // if every value in the second bag matches using the given // function, then return true, otherwise return false result = new EvaluationResult(BooleanAttribute.getInstance(true)); Iterator it = ((BagAttribute) args[0]).iterator(); BagAttribute bag = (BagAttribute) (args[1]); while (it.hasNext()) { AttributeValue value = (AttributeValue) (it.next()); result = all(value, bag, function, context); if (result.indeterminate()) return result; if (!((BooleanAttribute) (result.getAttributeValue())).getValue()) break; } break; } } return result; } /** * Checks that the given inputs are valid for this function. * * @param inputs a <code>List</code> of <code>Evaluatable</code>s * * @throws IllegalArgumentException if the inputs are invalid */ public void checkInputs(List inputs) throws IllegalArgumentException { Object[] list = inputs.toArray(); // first off, check that we got the right number of paramaters if (list.length != 3) throw new IllegalArgumentException("requires three inputs"); // now, try to cast the first element into a function Function function = null; if (list[0] instanceof Function) { function = (Function) (list[0]); } else if (list[0] instanceof VariableReference) { Expression xpr = ((VariableReference) (list[0])).getReferencedDefinition() .getExpression(); if (xpr instanceof Function) function = (Function) xpr; } if (function == null) throw new IllegalArgumentException("first arg to higher-order " + " function must be a function"); // check that the function returns a boolean if (!function.getReturnType().toString().equals(BooleanAttribute.identifier)) throw new IllegalArgumentException("higher-order function must " + "use a boolean function"); // get the two inputs Evaluatable eval1 = (Evaluatable) (list[1]); Evaluatable eval2 = (Evaluatable) (list[2]); // the first arg might be a bag if (secondIsBag && (!eval1.returnsBag())) throw new IllegalArgumentException("first arg has to be a bag"); // the second arg must be a bag if (!eval2.returnsBag()) throw new IllegalArgumentException("second arg has to be a bag"); // finally, we need to make sure that the given type will work on // the given function List args = new ArrayList(); args.add(eval1); args.add(eval2); function.checkInputsNoBag(args); } /** * Checks that the given inputs are valid for this function if all inputs are considered to not * be bags. This always throws an exception, since this function by definition must work on * bags. * * @param inputs a <code>List</code> of <code>Evaluatable</code>s * * @throws IllegalArgumentException always */ public void checkInputsNoBag(List inputs) throws IllegalArgumentException { throw new IllegalArgumentException("higher-order functions require " + "use of bags"); } /** * Private helper function that performs the any function, but lets you swap the argument order * (so it can be used by any-of-all) */ private EvaluationResult any(AttributeValue value, BagAttribute bag, Function function, EvaluationCtx context, boolean argumentsAreSwapped) { return anyAndAllHelper(value, bag, function, context, false, argumentsAreSwapped); } /** * Private helper function that performs the all function */ private EvaluationResult all(AttributeValue value, BagAttribute bag, Function function, EvaluationCtx context) { return anyAndAllHelper(value, bag, function, context, true, false); } /** * Private helper for any & all functions */ private EvaluationResult anyAndAllHelper(AttributeValue value, BagAttribute bag, Function function, EvaluationCtx context, boolean allFunction, boolean argumentsAreSwapped) { BooleanAttribute attr = BooleanAttribute.getInstance(allFunction); Iterator it = bag.iterator(); while (it.hasNext()) { List<Evaluatable> params = new ArrayList<Evaluatable>(); if (!argumentsAreSwapped) { params.add(value); params.add((AttributeValue) (it.next())); } else { params.add((AttributeValue) (it.next())); params.add(value); } EvaluationResult result = function.evaluate(params, context); if (result.indeterminate()) return result; BooleanAttribute bool = (BooleanAttribute) (result.getAttributeValue()); if (bool.getValue() != allFunction) { attr = bool; break; } } return new EvaluationResult(attr); } /** * any-of-all */ private EvaluationResult anyOfAll(BagAttribute anyBag, BagAttribute allBag, Function function, EvaluationCtx context) { return allAnyHelper(anyBag, allBag, function, context, true); } /** * all-of-any */ private EvaluationResult allOfAny(BagAttribute anyBag, BagAttribute allBag, Function function, EvaluationCtx context) { return allAnyHelper(anyBag, allBag, function, context, false); } /** * Private helper for the all-of-any and any-of-all functions */ private EvaluationResult allAnyHelper(BagAttribute anyBag, BagAttribute allBag, Function function, EvaluationCtx context, boolean argumentsAreSwapped) { Iterator it = allBag.iterator(); while (it.hasNext()) { AttributeValue value = (AttributeValue) (it.next()); EvaluationResult result = any(value, anyBag, function, context, argumentsAreSwapped); if (result.indeterminate()) return result; if (!((BooleanAttribute) (result.getAttributeValue())).getValue()) return result; } return new EvaluationResult(BooleanAttribute.getTrueInstance()); } /** * Encodes this <code>HigherOrderFunction</code> into its XML form * * @return <code>String</code> */ public String encode() { StringBuilder builder = new StringBuilder(); encode(builder); return builder.toString(); } /** * Encodes this <code>HigherOrderFunction</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("<Function FunctionId=\"").append(getIdentifier().toString()).append("\"/>\n"); } }
17,290
30.610603
106
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/FunctionFactoryProxy.java
/* * @(#)FunctionFactoryProxy.java * * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.cond; /** * A simple proxy interface used to install new <code>FunctionFactory</code>s. The three kinds of * factory (Target, Condition, and General) are tied together in this interface because implementors * writing new factories should always implement all three types and provide them together. * * @since 1.2 * @author Seth Proctor */ public interface FunctionFactoryProxy { /** * Returns the Target version of an instance of the <code>FunctionFactory</code> for which this * is a proxy. * * @return a <code>FunctionFactory</code> instance */ public FunctionFactory getTargetFactory(); /** * Returns the Condition version of an instance of the <code>FunctionFactory</code> for which * this is a proxy. * * @return a <code>FunctionFactory</code> instance */ public FunctionFactory getConditionFactory(); /** * Returns the General version of an instance of the <code>FunctionFactory</code> for which this * is a proxy. * * @return a <code>FunctionFactory</code> instance */ public FunctionFactory getGeneralFactory(); }
2,984
39.890411
100
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/Expression.java
/* * @(#)Expression.java * * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.cond; import org.wso2.balana.Indenter; import java.net.URI; import java.io.OutputStream; /** * This interface represents the expression type in the XACML 2.0 schema. * * @since 2.0 * @author Seth Proctor */ public interface Expression { /** * Returns the type of the expression. This may be the data type of an * <code>AttributeValue</code>, the return type of a <code>Function</code>, etc. * * @return the attribute type of the referenced expression */ public URI getType(); /** * Returns whether or not this expression returns, or evaluates to a Bag. Note that * <code>Evaluatable</code>, which extends this interface, defines <code>evaluatesToBag</code> * which is essentially the same function. This method has been deprecated, and * <code>returnsBag</code> is now the preferred way to query all <code>Expression</code>s. */ public boolean returnsBag(); /** * Encodes this <code>AttributeValue</code> into its XML representation and writes this encoding * to the given <code>StringBuilder</code> This will always produce the version * used in a policy rather than that used in a request, so this is equivalent to calling * <code>encodeWithTags(true)</code> and then stuffing that into a stream. * * @param builder string stream into which the XML-encoded data is written */ public void encode(StringBuilder builder); }
3,284
40.582278
100
java
balana
balana-master/modules/balana-core/src/main/java/org/wso2/balana/cond/Evaluatable.java
/* * @(#)Evaluatable.java * * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package org.wso2.balana.cond; import org.wso2.balana.ctx.EvaluationCtx; import java.util.List; /** * Generic interface that is implemented by all objects that can be evaluated directly ( * <code>AttributeDesignator</code>, <code>Apply</code>, <code>AttributeValue</code>, etc.). As of * version 2.0 several methods were extracted to the new <code>Expression</code> super-interface. * * @since 1.0 * @author Seth Proctor */ public interface Evaluatable extends Expression { /** * Evaluates the object using the given context, and either returns an error or a resulting * value. * * @param context the representation of the request * * @return the result of evaluation */ public EvaluationResult evaluate(EvaluationCtx context); /** * Tells whether evaluation will return a bag or a single value. * * @deprecated As of 2.0, you should use the <code>returnsBag</code> method from the * super-interface <code>Expression</code>. * * @return true if evaluation will return a bag, false otherwise */ public boolean evaluatesToBag(); /** * Returns all children, in order, of this element in the Condition tree, or en empty set if * this element has no children. In XACML 1.x, only the ApplyType ever has children. * * @return a <code>List</code> of <code>Evaluatable</code>s */ public List getChildren(); }
3,269
39.37037
98
java