diff options
author | Pamela Dragosh <pdragosh@research.att.com> | 2019-03-09 11:48:44 -0500 |
---|---|---|
committer | Pamela Dragosh <pdragosh@research.att.com> | 2019-03-15 08:54:05 -0400 |
commit | b909b14fe88c5fe8f096cf8b471a2aa799d84739 (patch) | |
tree | 19de65fff7618bfad91acb0b803210a93dbb86cd /applications/common | |
parent | 4b2ef1a5a9bf92aeb7edc1512f7a6cd8e1be99d8 (diff) |
Monitoring policy creation foundation
Upgrde to xacml v2.0.0 release artifact.
Some re-arrangement of classes. New class to support a
common dictionary among the monitoring applications. I
may move it to a common under the main since some of the
values are shareable.
Created application service provider, so the XACML
main knows what policy types are pre-loaded and can
report them back to the PAP.
struggled with cucumber, which does not create
TemporaryFolder although the documentation says its
supported.
Added a new Policy Finder specific to ONAP which does
quicker job to load policies.
Issue-ID: POLICY-1273
Change-Id: I4af15a64da3b42d48f29809710421b1649625adc
Signed-off-by: Pamela Dragosh <pdragosh@research.att.com>
Diffstat (limited to 'applications/common')
13 files changed, 1132 insertions, 0 deletions
diff --git a/applications/common/pom.xml b/applications/common/pom.xml new file mode 100644 index 00000000..9d83f3d5 --- /dev/null +++ b/applications/common/pom.xml @@ -0,0 +1,46 @@ +<!-- + ============LICENSE_START======================================================= + ONAP + ================================================================================ + Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + ================================================================================ + Licensed 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. + ============LICENSE_END========================================================= + --> + +<project + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" + xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.onap.policy.xacml-pdp.applications</groupId> + <artifactId>applications</artifactId> + <version>2.0.0-SNAPSHOT</version> + </parent> + + <artifactId>common</artifactId> + + <dependencies> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.common</groupId> + <artifactId>utils-test</artifactId> + <version>${policy.common.version}</version> + </dependency> + </dependencies> +</project> diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/OnapPolicyFinderFactory.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/OnapPolicyFinderFactory.java new file mode 100644 index 00000000..1e47c5b5 --- /dev/null +++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/OnapPolicyFinderFactory.java @@ -0,0 +1,252 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + + +package org.onap.policy.pdp.xacml.application.common; + +import com.att.research.xacml.std.StdStatusCode; +import com.att.research.xacml.std.dom.DOMStructureException; +import com.att.research.xacml.util.FactoryException; +import com.att.research.xacml.util.XACMLProperties; +import com.att.research.xacmlatt.pdp.policy.Policy; +import com.att.research.xacmlatt.pdp.policy.PolicyDef; +import com.att.research.xacmlatt.pdp.policy.PolicyFinder; +import com.att.research.xacmlatt.pdp.policy.PolicyFinderFactory; +import com.att.research.xacmlatt.pdp.policy.dom.DOMPolicyDef; +import com.att.research.xacmlatt.pdp.std.StdPolicyFinder; +import com.google.common.base.Splitter; +import com.google.common.base.Strings; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Properties; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Implements ONAP specific ability to find Policies for XACML PDP engine. + * + * @author pameladragosh + * + */ +public class OnapPolicyFinderFactory extends PolicyFinderFactory { + + public static final String PROP_FILE = ".file"; + public static final String PROP_URL = ".url"; + + private static Logger logger = LoggerFactory.getLogger(OnapPolicyFinderFactory.class); + private List<PolicyDef> rootPolicies; + private List<PolicyDef> referencedPolicies; + private boolean needsInit = true; + + private Properties properties = null; + + /** + * Empty constructor. + */ + public OnapPolicyFinderFactory() { + logger.debug("Constructed without properties"); + // + // Here we differ from the StdPolicyFinderFactory in that we initialize right away. + // We do not wait for a policy request to happen to look for and load policies. + // + this.init(); + } + + /** + * Constructor with properties passed. This will be preferred. + * + * @param properties Properties object + */ + public OnapPolicyFinderFactory(Properties properties) { + super(properties); + logger.debug("Constructed using properties {}", properties); + // + // Save our properties + // + this.properties = properties; + // + // Here we differ from the StdPolicyFinderFactory in that we initialize right away. + // We do not wait for a policy request to happen to look for and load policies. + // + this.init(); + } + + /** + * Loads the <code>PolicyDef</code> for the given <code>String</code> identifier by looking first + * for a ".file" property associated with the ID and using that to load from a <code>File</code> and + * looking for a ".url" property associated with the ID and using that to load from a <code>URL</code>. + * + * @param policyId the <code>String</code> identifier for the policy + * @return a <code>PolicyDef</code> loaded from the given identifier + */ + protected PolicyDef loadPolicyDef(String policyId) { + String propLocation = null; + if (this.properties == null) { + propLocation = XACMLProperties.getProperty(policyId + PROP_FILE); + } else { + propLocation = this.properties.getProperty(policyId + PROP_FILE); + } + if (propLocation != null) { + // + // Try to load it from the file + // + PolicyDef policy = this.loadPolicyFileDef(propLocation); + if (policy != null) { + return policy; + } + } + if (this.properties == null) { + propLocation = XACMLProperties.getProperty(policyId + PROP_URL); + } else { + propLocation = this.properties.getProperty(policyId + PROP_URL); + } + if (propLocation != null) { + PolicyDef policy = this.loadPolicyUrlDef(propLocation); + if (policy != null) { + return policy; + } + } + + logger.error("No known location for Policy {}", policyId); + return null; + } + + protected PolicyDef loadPolicyFileDef(String propLocation) { + File fileLocation = new File(propLocation); + if (!fileLocation.exists()) { + logger.error("Policy file {} does not exist.", fileLocation.getAbsolutePath()); + return null; + } + if (!fileLocation.canRead()) { + logger.error("Policy file {} cannot be read.", fileLocation.getAbsolutePath()); + return null; + } + try { + logger.info("Loading policy file {}", fileLocation); + PolicyDef policyDef = DOMPolicyDef.load(fileLocation); + if (policyDef != null) { + return policyDef; + } + return new Policy(StdStatusCode.STATUS_CODE_SYNTAX_ERROR, "DOM Could not load policy"); + } catch (DOMStructureException ex) { + logger.error("Error loading policy file {}: {}", fileLocation.getAbsolutePath(), ex); + return new Policy(StdStatusCode.STATUS_CODE_SYNTAX_ERROR, ex.getMessage()); + } + } + + protected PolicyDef loadPolicyUrlDef(String propLocation) { + InputStream is = null; + try { + URL url = new URL(propLocation); + URLConnection urlConnection = url.openConnection(); + OnapPolicyFinderFactory.logger.info("Loading policy file {}", url); + is = urlConnection.getInputStream(); + PolicyDef policyDef = DOMPolicyDef.load(is); + if (policyDef != null) { + return policyDef; + } + } catch (MalformedURLException ex) { + logger.error("Invalid URL " + propLocation + ": " + ex.getMessage(), ex); + } catch (IOException ex) { + logger.error("IOException opening URL {}: {}{}", + propLocation, ex.getMessage(), ex); + } catch (DOMStructureException ex) { + logger.error("Invalid Policy " + propLocation + ": " + ex.getMessage(), ex); + return new Policy(StdStatusCode.STATUS_CODE_SYNTAX_ERROR, ex.getMessage()); + } finally { + if (is != null) { + try { + is.close(); + } catch (IOException e) { + logger.error("Exception closing InputStream for GET of url {}: {}", + propLocation, e.getMessage() + " (May be memory leak)", e); + } + } + } + return null; + } + + /** + * Finds the identifiers for all of the policies referenced by the given property name in the + * <code>XACMLProperties</code> and loads them using the requested loading method. + * + * @param propertyName the <code>String</code> name of the property containing the list of policy identifiers + * @return a <code>List</code> of <code>PolicyDef</code>s loaded from the given property name + */ + protected List<PolicyDef> getPolicyDefs(String propertyName) { + String policyIds; + if (this.properties != null) { + policyIds = this.properties.getProperty(propertyName); + } else { + policyIds = XACMLProperties.getProperty(propertyName); + } + if (Strings.isNullOrEmpty(policyIds)) { + return Collections.emptyList(); + } + + Iterable<String> policyIdArray = Splitter.on(',').trimResults().omitEmptyStrings().split(policyIds); + if (policyIdArray == null) { + return Collections.emptyList(); + } + + List<PolicyDef> listPolicyDefs = new ArrayList<>(); + for (String policyId : policyIdArray) { + PolicyDef policyDef = this.loadPolicyDef(policyId); + if (policyDef != null) { + listPolicyDefs.add(policyDef); + } + } + return listPolicyDefs; + } + + protected synchronized void init() { + if (this.needsInit) { + logger.debug("Initializing OnapPolicyFinderFactory Properties "); + this.rootPolicies = this.getPolicyDefs(XACMLProperties.PROP_ROOTPOLICIES); + this.referencedPolicies = this.getPolicyDefs(XACMLProperties.PROP_REFERENCEDPOLICIES); + logger.debug("Root Policies: {}", this.rootPolicies.size()); + logger.debug("Referenced Policies: {}", this.referencedPolicies.size()); + this.needsInit = false; + } + } + + @Override + public PolicyFinder getPolicyFinder() throws FactoryException { + // + // Force using any properties that were passed upon construction + // + return new StdPolicyFinder(this.rootPolicies, this.referencedPolicies, this.properties); + } + + @Override + public PolicyFinder getPolicyFinder(Properties properties) throws FactoryException { + return new StdPolicyFinder(this.rootPolicies, this.referencedPolicies, properties); + } + +} diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaDictionary.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaDictionary.java new file mode 100644 index 00000000..c65d7a17 --- /dev/null +++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaDictionary.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pdp.xacml.application.common; + +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.std.IdentifierImpl; + +public final class ToscaDictionary { + + private ToscaDictionary() { + super(); + } + + /* + * These are the ID's for various TOSCA Policy Types we are supporting in the Applications. + */ + public static final Identifier URN_ONAP = + new IdentifierImpl("urn:org:onap"); + + public static final Identifier ID_RESOURCE_POLICY_ID = + XACML3.ID_RESOURCE_RESOURCE_ID; + + public static final Identifier ID_RESOURCE_POLICY_TYPE = + new IdentifierImpl(URN_ONAP, "policy-type"); + + public static final Identifier ID_RESOURCE_POLICY_TYPE_VERSION = + new IdentifierImpl(URN_ONAP, "policy-type-version"); + + public static final Identifier ID_OBLIGATION_REST_BODY = + new IdentifierImpl(URN_ONAP, "rest:body"); + + public static final Identifier ID_OBLIGATION_POLICY_MONITORING = + new IdentifierImpl(URN_ONAP, ":obligation:monitoring"); + + public static final Identifier ID_OBLIGATION_POLICY_MONITORING_CONTENTS = + new IdentifierImpl(URN_ONAP, ":obligation:monitoring:contents"); + + public static final Identifier ID_OBLIGATION_POLICY_MONITORING_CATEGORY = + XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE; + + public static final Identifier ID_OBLIGATION_POLICY_MONITORING_DATATYPE = + XACML3.ID_DATATYPE_STRING; + + public static final Identifier ID_OBLIGATION_ISSUER = + new IdentifierImpl(URN_ONAP, "issuer:monitoring"); + + +} diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConversionException.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConversionException.java new file mode 100644 index 00000000..071a14e1 --- /dev/null +++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConversionException.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pdp.xacml.application.common; + +public class ToscaPolicyConversionException extends Exception { + + private static final long serialVersionUID = 1L; + + public ToscaPolicyConversionException() { + super(); + } + + public ToscaPolicyConversionException(String message) { + super(message); + } + + public ToscaPolicyConversionException(Throwable cause) { + super(cause); + } + + public ToscaPolicyConversionException(String message, Throwable cause) { + super(message, cause); + } + + public ToscaPolicyConversionException(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + +} diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConverter.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConverter.java new file mode 100644 index 00000000..f6f75a4c --- /dev/null +++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConverter.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pdp.xacml.application.common; + +import java.io.InputStream; +import java.util.List; +import java.util.Map; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; + +public interface ToscaPolicyConverter { + + List<PolicyType> convertPolicies(InputStream isToscaPolicy) throws ToscaPolicyConversionException; + + List<PolicyType> convertPolicies(Map<String, Object> toscaObject) throws ToscaPolicyConversionException; +} diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConverterUtils.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConverterUtils.java new file mode 100644 index 00000000..cd197935 --- /dev/null +++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConverterUtils.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pdp.xacml.application.common; + +import com.att.research.xacml.api.Identifier; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; + +/** + * This class contains static methods of helper classes to convert TOSCA policies + * into XACML policies. + * + * @author pameladragosh + * + */ +public final class ToscaPolicyConverterUtils { + + private ToscaPolicyConverterUtils() { + super(); + } + + /** + * This method builds a MatchType for TargetType object for AttributeValue and AttributeDesignator + * combination. + * + * @param <T> Incoming value could be any object + * @param function Function for the Match + * @param value Attribute value used + * @param datatype Datatype for attribute value and AttributeDesignator + * @param designatorId ID for the AttributeDesignator + * @param designatorCategory Category ID for the AttributeDesignator + * @return The MatchType object + */ + public static <T> MatchType buildMatchTypeDesignator(Identifier function, + T value, + Identifier datatype, + Identifier designatorId, + Identifier designatorCategory) { + // + // Create the MatchType object and set its function + // + MatchType match = new MatchType(); + match.setMatchId(function.stringValue()); + // + // Add in the AttributeValue object + // + AttributeValueType valueType = new AttributeValueType(); + valueType.setDataType(datatype.stringValue()); + valueType.getContent().add(value); + + match.setAttributeValue(valueType); + // + // Add in the AttributeDesignator object + // + AttributeDesignatorType designator = new AttributeDesignatorType(); + designator.setAttributeId(designatorId.stringValue()); + designator.setCategory(designatorCategory.stringValue()); + designator.setDataType(datatype.stringValue()); + + match.setAttributeDesignator(designator); + // + // Done + // + return match; + } + + /** + * Builds an AllOfType (AND) with one or more MatchType objects. + * + * @param matches A list of one or more MatchType + * @return The AllOf object + */ + public static AllOfType buildAllOf(MatchType... matches) { + AllOfType allOf = new AllOfType(); + for (MatchType match : matches) { + allOf.getMatch().add(match); + } + return allOf; + } +} diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/XacmlApplicationServiceProvider.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/XacmlApplicationServiceProvider.java new file mode 100644 index 00000000..65648ea8 --- /dev/null +++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/XacmlApplicationServiceProvider.java @@ -0,0 +1,98 @@ +/* ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pdp.xacml.application.common; + +import java.nio.file.Path; +import java.util.List; +import java.util.Map; + +import org.json.JSONObject; + +/** + * This interface is how the XACML REST controller can communicate + * with Policy Type implementation applications. + * Applications should register themselves as this service provider + * and implement these methods. + * + * @author pameladragosh + * + */ +public interface XacmlApplicationServiceProvider { + + /** + * Name of the application for auditing and organization of its data. + * + * @return String + */ + String applicationName(); + + /** + * Returns a list of action decisions supported by the application. + * + * @return List of String (eg. "configure", "placement", "naming") + */ + List<String> actionDecisionsSupported(); + + /** + * Initializes the application and gives it a Path for storing its + * data. The Path may be already populated with previous data. + * + * @param pathForData Local Path + */ + void initialize(Path pathForData); + + /** + * Returns a list of supported Tosca Policy Types. + * + * @return List of Strings (eg. "onap.policy.foo.bar") + */ + List<String> supportedPolicyTypes(); + + /** + * Asks whether the application can support the incoming + * Tosca Policy Type and version. + * + * @param policyType String Tosca Policy Type + * @param policyTypeVersion String of the Tosca Policy Type version + * @return true if supported + */ + boolean canSupportPolicyType(String policyType, String policyTypeVersion); + + /** + * Load a Map representation of a Tosca Policy. + * + * @param toscaPolicies Map of Tosca Policy Objects + */ + void loadPolicies(Map<String, Object> toscaPolicies); + + /** + * Makes a decision given the incoming request and returns a response. + * + * <P>NOTE: I may want to change this to an object that represents the + * schema. + * + * @param jsonSchema Incoming Json + * @return response + */ + JSONObject makeDecision(JSONObject jsonSchema); + +} diff --git a/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/XacmlUpdatePolicyUtils.java b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/XacmlUpdatePolicyUtils.java new file mode 100644 index 00000000..957242c5 --- /dev/null +++ b/applications/common/src/main/java/org/onap/policy/pdp/xacml/application/common/XacmlUpdatePolicyUtils.java @@ -0,0 +1,88 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pdp.xacml.application.common; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.IdReferenceType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; + +public class XacmlUpdatePolicyUtils { + + private XacmlUpdatePolicyUtils() { + super(); + } + + /** + * This method updates a root PolicySetType by adding in a PolicyType as a reference. + * + * @param rootPolicy Root PolicySet being updated + * @param referencedPolicies A list of PolicyType being added as a references + * @return the rootPolicy PolicySet object + */ + public static PolicySetType updateXacmlRootPolicy(PolicySetType rootPolicy, PolicyType... referencedPolicies) { + ObjectFactory factory = new ObjectFactory(); + // + // Iterate each policy + // + for (PolicyType referencedPolicy : referencedPolicies) { + IdReferenceType reference = new IdReferenceType(); + reference.setValue(referencedPolicy.getPolicyId()); + // + // Add it in + // + rootPolicy.getPolicySetOrPolicyOrPolicySetIdReference().add(factory.createPolicySetIdReference(reference)); + } + // + // Return the updated object + // + return rootPolicy; + } + + /** + * This method updates a root PolicySetType by adding in a PolicyType as a reference. + * + * @param rootPolicy Root PolicySet being updated + * @param referencedPolicySets A list of PolicySetType being added as a references + * @return the rootPolicy PolicySet object + */ + public static PolicySetType updateXacmlRootPolicy(PolicySetType rootPolicy, PolicySetType... referencedPolicySets) { + ObjectFactory factory = new ObjectFactory(); + // + // Iterate each policy + // + for (PolicySetType referencedPolicySet : referencedPolicySets) { + IdReferenceType reference = new IdReferenceType(); + reference.setValue(referencedPolicySet.getPolicySetId()); + // + // Add it in + // + rootPolicy.getPolicySetOrPolicyOrPolicySetIdReference().add(factory.createPolicySetIdReference(reference)); + } + // + // Return the updated object + // + return rootPolicy; + } + +} diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaDictionaryTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaDictionaryTest.java new file mode 100644 index 00000000..d427982f --- /dev/null +++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaDictionaryTest.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pdp.xacml.application.common; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Modifier; + +import org.junit.Test; + +public class ToscaDictionaryTest { + + @Test + public void testConstructorIsProtected() throws Exception { + // + // Ensure that this is static class + // + final Constructor<ToscaDictionary> constructor = ToscaDictionary.class.getDeclaredConstructor(); + assertTrue(Modifier.isPrivate(constructor.getModifiers())); + // + // Trying to get 100% code coverage + // + assertThatCode(() -> { + constructor.setAccessible(true); + constructor.newInstance(); + }).doesNotThrowAnyException(); + // + // Probably don't need these as these ID's are used by other components + // + assertNotNull(ToscaDictionary.ID_OBLIGATION_ISSUER); + } + +} diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConversionExceptionTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConversionExceptionTest.java new file mode 100644 index 00000000..bee4ba3d --- /dev/null +++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConversionExceptionTest.java @@ -0,0 +1,35 @@ +/* + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pdp.xacml.application.common; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.onap.policy.common.utils.test.ExceptionsTester; + +public class ToscaPolicyConversionExceptionTest { + + @Test + public void test() { + assertEquals(5, new ExceptionsTester().test(ToscaPolicyConversionException.class)); + } + +} diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConverterUtilsTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConverterUtilsTest.java new file mode 100644 index 00000000..cc1787c3 --- /dev/null +++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/ToscaPolicyConverterUtilsTest.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pdp.xacml.application.common; + +import static org.junit.Assert.assertTrue; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Modifier; + +import org.junit.Test; + +public class ToscaPolicyConverterUtilsTest { + + @Test + public void test() throws NoSuchMethodException, SecurityException { + final Constructor<ToscaPolicyConverterUtils> constructor + = ToscaPolicyConverterUtils.class.getDeclaredConstructor(); + assertTrue(Modifier.isPrivate(constructor.getModifiers())); + + } + +} diff --git a/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/XacmlUpdatePolicyUtilsTest.java b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/XacmlUpdatePolicyUtilsTest.java new file mode 100644 index 00000000..84fefa5c --- /dev/null +++ b/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/XacmlUpdatePolicyUtilsTest.java @@ -0,0 +1,226 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pdp.xacml.application.common; + +import static org.assertj.core.api.Assertions.assertThatCode; + +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.util.XACMLPolicyWriter; +import com.att.research.xacml.util.XACMLProperties; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map.Entry; +import java.util.Properties; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import org.junit.BeforeClass; +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Utility methods for storing policies to disk and updating Properties objects + * that reference policies. + * + * @author pameladragosh + * + */ +public class XacmlUpdatePolicyUtilsTest { + private static final Logger LOGGER = LoggerFactory.getLogger(XacmlUpdatePolicyUtilsTest.class); + + static Properties properties; + + static PolicySetType rootPolicy = new PolicySetType(); + + static Path rootPath; + + static PolicyType policy1 = new PolicyType(); + static PolicyType policy2 = new PolicyType(); + + static PolicySetType policySet3 = new PolicySetType(); + + static Path path1; + static Path path2; + + static Path policySetPath; + + /** + * Temporary folder where we will store newly created policies. + */ + @ClassRule + public static TemporaryFolder policyFolder = new TemporaryFolder(); + + /** + * Setup the JUnit tests. + * + * @throws Exception thrown + */ + @BeforeClass + public static void setUp() throws Exception { + assertThatCode(() -> { + // + // Load our test property object + // + try (InputStream is = new FileInputStream("src/test/resources/test.properties")) { + properties = new Properties(); + properties.load(is); + } + // + // Create a very basic Root policy + // + rootPolicy.setPolicySetId("root"); + rootPolicy.setTarget(new TargetType()); + rootPolicy.setPolicyCombiningAlgId(XACML3.ID_POLICY_FIRST_APPLICABLE.stringValue()); + File rootFile = policyFolder.newFile("root.xml"); + LOGGER.info("Creating Root Policy {}", rootFile.getAbsolutePath()); + rootPath = XACMLPolicyWriter.writePolicyFile(rootFile.toPath(), rootPolicy); + // + // Create policies + // + path1 = createPolicy(policy1, "policy1", "resource1"); + LOGGER.info(new String(Files.readAllBytes(path1))); + path2 = createPolicy(policy2, "policy2", "resource2"); + LOGGER.info(new String(Files.readAllBytes(path2))); + // + // Create another PolicySet + // + policySet3.setPolicySetId("policyset1"); + policySet3.setTarget(new TargetType()); + policySet3.setPolicyCombiningAlgId(XACML3.ID_POLICY_FIRST_APPLICABLE.stringValue()); + ObjectFactory factory = new ObjectFactory(); + + policySet3.getPolicySetOrPolicyOrPolicySetIdReference().add(factory.createPolicy(policy1)); + policySet3.getPolicySetOrPolicyOrPolicySetIdReference().add(factory.createPolicy(policy2)); + File policySetFile = policyFolder.newFile("policySet1.xml"); + LOGGER.info("Creating PolicySet {}", policySetFile.getAbsolutePath()); + policySetPath = XACMLPolicyWriter.writePolicyFile(policySetFile.toPath(), policySet3); + + }).doesNotThrowAnyException(); + } + + private static Path createPolicy(PolicyType policy, String id, String resource) throws IOException { + // + // Create Policy 1 + // + policy.setPolicyId(id); + MatchType matchPolicyId = ToscaPolicyConverterUtils.buildMatchTypeDesignator( + XACML3.ID_FUNCTION_STRING_EQUAL, + resource, + XACML3.ID_DATATYPE_STRING, + XACML3.ID_RESOURCE_RESOURCE_ID, + XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE); + // + // This is our outer AnyOf - which is an OR + // + AnyOfType anyOf = new AnyOfType(); + // + // Create AllOf (AND) of just Policy Id + // + anyOf.getAllOf().add(ToscaPolicyConverterUtils.buildAllOf(matchPolicyId)); + TargetType target = new TargetType(); + target.getAnyOf().add(anyOf); + policy.setTarget(target); + RuleType rule = new RuleType(); + rule.setRuleId(policy.getPolicyId() + ":rule"); + rule.setEffect(EffectType.PERMIT); + rule.setTarget(new TargetType()); + // + // Add the rule to the policy + // + policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); + // + // Create a file + // + File file = policyFolder.newFile(policy.getPolicyId() + ".xml"); + LOGGER.info("Creating Policy {}", file.getAbsolutePath()); + return XACMLPolicyWriter.writePolicyFile(file.toPath(), policy); + } + + @Test + public void test() { + assertThatCode(() -> { + // + // Just update root and policies + // + XacmlUpdatePolicyUtils.updateXacmlRootPolicy(rootPolicy, policy1, policy2); + try (OutputStream os = new ByteArrayOutputStream()) { + XACMLPolicyWriter.writePolicyFile(os, rootPolicy); + LOGGER.debug("New Root Policy:{}{}", System.lineSeparator(), os.toString()); + } + // + // Test updating the properties + // + XACMLProperties.setXacmlRootProperties(properties, rootPath); + XACMLProperties.setXacmlReferencedProperties(properties, path1, path2); + // + // Dump this out so I can see what I'm doing + // + for (Entry<Object, Object> entry : properties.entrySet()) { + LOGGER.info("{}={}", entry.getKey(), entry.getValue()); + } + LOGGER.info("Properties {}", properties.toString()); + // + // Somehow I have to figure out how to test this in assertj + // + // + // Just update root and PolicySet + // + XacmlUpdatePolicyUtils.updateXacmlRootPolicy(rootPolicy, policySet3); + try (OutputStream os = new ByteArrayOutputStream()) { + XACMLPolicyWriter.writePolicyFile(os, rootPolicy); + LOGGER.debug("New Root Policy:{}{}", System.lineSeparator(), os.toString()); + } + // + // Test updating the properties + // + XACMLProperties.setXacmlRootProperties(properties, rootPath); + XACMLProperties.setXacmlReferencedProperties(properties, policySetPath); + // + // Dump this out so I can see what I'm doing + // + for (Entry<Object, Object> entry : properties.entrySet()) { + LOGGER.info("{}={}", entry.getKey(), entry.getValue()); + } + LOGGER.info("Properties {}", properties.toString()); + // + // Somehow I have to figure out how to test this in assertj + // + + }).doesNotThrowAnyException(); + } +} diff --git a/applications/common/src/test/resources/test.properties b/applications/common/src/test/resources/test.properties new file mode 100644 index 00000000..efe90d82 --- /dev/null +++ b/applications/common/src/test/resources/test.properties @@ -0,0 +1,32 @@ +# +# Properties that the embedded PDP engine uses to configure and load +# +# Standard API Factories +# +xacml.dataTypeFactory=com.att.research.xacml.std.StdDataTypeFactory +xacml.pdpEngineFactory=com.att.research.xacmlatt.pdp.ATTPDPEngineFactory +xacml.pepEngineFactory=com.att.research.xacml.std.pep.StdEngineFactory +xacml.pipFinderFactory=com.att.research.xacml.std.pip.StdPIPFinderFactory +xacml.traceEngineFactory=com.att.research.xacml.std.trace.LoggingTraceEngineFactory +# +# AT&T PDP Implementation Factories +# +xacml.att.evaluationContextFactory=com.att.research.xacmlatt.pdp.std.StdEvaluationContextFactory +xacml.att.combiningAlgorithmFactory=com.att.research.xacmlatt.pdp.std.StdCombiningAlgorithmFactory +xacml.att.functionDefinitionFactory=com.att.research.xacmlatt.pdp.std.StdFunctionDefinitionFactory +# +# ONAP PDP Implementation Factories +# +xacml.att.policyFinderFactory=org.onap.policy.pdp.xacml.application.common.OnapPolicyFinderFactory + +# +# +# +xacml.rootPolicies=rootstart +rootstart.file=src/test/resources/root.xml + +xacml.referencedPolicies=refstart1,refstart2,refstart3,refstart4 +refstart1.file=src/test/resources/ref1.xml +refstart2.file=src/test/resources/ref2.xml +refstart3.file=src/test/resources/ref3.xml +refstart4.file=src/test/resources/ref4.xml |