318d9f9f6e6921ec30e8532f2315b7baeeb0c27b
[policy/xacml-pdp.git] / applications / common / src / test / java / org / onap / policy / pdp / xacml / application / common / XacmlPolicyUtilsTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.pdp.xacml.application.common;
24
25 import static org.assertj.core.api.Assertions.assertThat;
26 import static org.assertj.core.api.Assertions.assertThatCode;
27
28 import com.att.research.xacml.api.XACML3;
29 import com.att.research.xacml.util.XACMLPolicyWriter;
30
31 import java.io.ByteArrayOutputStream;
32 import java.io.File;
33 import java.io.FileInputStream;
34 import java.io.IOException;
35 import java.io.InputStream;
36 import java.io.OutputStream;
37 import java.nio.file.Files;
38 import java.nio.file.Path;
39 import java.nio.file.Paths;
40 import java.util.List;
41 import java.util.Properties;
42 import java.util.stream.Collectors;
43 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
51
52 import org.junit.BeforeClass;
53 import org.junit.ClassRule;
54 import org.junit.Test;
55 import org.junit.rules.TemporaryFolder;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 /**
60  * Utility methods for storing policies to disk and updating Properties objects
61  * that reference policies.
62  *
63  * @author pameladragosh
64  *
65  */
66 public class XacmlPolicyUtilsTest {
67     private static final Logger LOGGER = LoggerFactory.getLogger(XacmlPolicyUtilsTest.class);
68
69     static Properties properties;
70
71     static PolicySetType rootPolicy = XacmlPolicyUtils.createEmptyPolicySet("root", XACML3.ID_POLICY_FIRST_APPLICABLE);
72
73     static Path rootPath;
74
75     static PolicyType policy1 = XacmlPolicyUtils.createEmptyPolicy("policy1", XACML3.ID_RULE_DENY_UNLESS_PERMIT);
76     static PolicyType policy2 = XacmlPolicyUtils.createEmptyPolicy("policy2", XACML3.ID_RULE_DENY_UNLESS_PERMIT);
77     static PolicyType policy3 = XacmlPolicyUtils.createEmptyPolicy("policy3", XACML3.ID_RULE_DENY_UNLESS_PERMIT);
78     static PolicyType policy4 = XacmlPolicyUtils.createEmptyPolicy("policy4", XACML3.ID_RULE_DENY_UNLESS_PERMIT);
79
80     static PolicySetType policySet5 = XacmlPolicyUtils.createEmptyPolicySet(
81             "policyset1", XACML3.ID_POLICY_FIRST_APPLICABLE);
82
83     static Path path1;
84     static Path path2;
85     static Path path3;
86     static Path path4;
87
88     static Path policySetPath;
89
90     /**
91      * Temporary folder where we will store newly created policies.
92      */
93     @ClassRule
94     public static TemporaryFolder policyFolder = new TemporaryFolder();
95
96     /**
97      * Setup the JUnit tests by finishing creating the policies and
98      * writing them out to the temporary folder.
99      *
100      * @throws Exception thrown
101      */
102     @BeforeClass
103     public static void setUp() throws Exception {
104         assertThatCode(() -> {
105             //
106             // Load our test property object
107             //
108             try (InputStream is = new FileInputStream("src/test/resources/test.properties")) {
109                 properties = new Properties();
110                 properties.load(is);
111             }
112             //
113             // Change "/" to file separator in file names
114             //
115             if (!"/".equals(File.separator)) {
116                 List<String> fileProps = properties.keySet().stream().map(Object::toString)
117                                 .filter(key -> key.endsWith(".file")).collect(Collectors.toList());
118                 for (String fileProp : fileProps) {
119                     properties.setProperty(fileProp, properties.getProperty(fileProp).replace("/", File.separator));
120                 }
121             }
122             //
123             // Save root policy
124             //
125             File rootFile = policyFolder.newFile("root.xml");
126             LOGGER.info("Creating Root Policy {}", rootFile.getAbsolutePath());
127             rootPath = XACMLPolicyWriter.writePolicyFile(rootFile.toPath(), rootPolicy);
128             //
129             // Create policies - Policies 1 and 2 will become references in the
130             // root policy. While Policies 3 and 4 will become references in the
131             // soon to be created PolicySet 5 below.
132             //
133             path1 = createPolicyContents(policy1, "resource1");
134             LOGGER.info(new String(Files.readAllBytes(path1)));
135             path2 = createPolicyContents(policy2, "resource2");
136             LOGGER.info(new String(Files.readAllBytes(path2)));
137             path3 = createPolicyContents(policy3, "resourc31");
138             LOGGER.info(new String(Files.readAllBytes(path3)));
139             path4 = createPolicyContents(policy4, "resource4");
140             LOGGER.info(new String(Files.readAllBytes(path4)));
141             //
142             // Create our PolicySet
143             //
144             policySet5.setPolicySetId("policyset5");
145             policySet5.setTarget(new TargetType());
146             policySet5.setPolicyCombiningAlgId(XACML3.ID_POLICY_FIRST_APPLICABLE.stringValue());
147             ObjectFactory factory = new ObjectFactory();
148             //
149             // Add Policies 3 and 4 to the PolicySet
150             //
151             policySet5.getPolicySetOrPolicyOrPolicySetIdReference().add(factory.createPolicy(policy1));
152             policySet5.getPolicySetOrPolicyOrPolicySetIdReference().add(factory.createPolicy(policy2));
153             assertThat(policySet5.getPolicySetOrPolicyOrPolicySetIdReference()).hasSize(2);
154             //
155             // Save that to disk
156             //
157             File policySetFile = policyFolder.newFile("policySet5.xml");
158             LOGGER.info("Creating PolicySet {}", policySetFile.getAbsolutePath());
159             policySetPath = XACMLPolicyWriter.writePolicyFile(policySetFile.toPath(), policySet5);
160
161         }).doesNotThrowAnyException();
162     }
163
164     /**
165      * Helper method that creates a very simple Policy and Rule and saves it to disk.
166      *
167      * @param policy Policy to store contents in
168      * @param resource A simple resource id for the Target
169      * @return Path object of the policy
170      * @throws IOException If unable to write to disk
171      */
172     private static Path createPolicyContents(PolicyType policy, String resource) throws IOException {
173         //
174         // Create The Match
175         //
176         MatchType matchPolicyId = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
177                 XACML3.ID_FUNCTION_STRING_EQUAL,
178                 resource,
179                 XACML3.ID_DATATYPE_STRING,
180                 XACML3.ID_RESOURCE_RESOURCE_ID,
181                 XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);
182         //
183         // This is our outer AnyOf - which is an OR
184         //
185         AnyOfType anyOf = new AnyOfType();
186         //
187         // Create AllOf (AND) of just Policy Id
188         //
189         anyOf.getAllOf().add(ToscaPolicyTranslatorUtils.buildAllOf(matchPolicyId));
190         TargetType target = new TargetType();
191         target.getAnyOf().add(anyOf);
192         policy.setTarget(target);
193         RuleType rule = new RuleType();
194         rule.setRuleId(policy.getPolicyId() + ":rule");
195         rule.setEffect(EffectType.PERMIT);
196         rule.setTarget(new TargetType());
197         //
198         // Add the rule to the policy
199         //
200         policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
201         //
202         // Save it to disk
203         //
204         File file = policyFolder.newFile(policy.getPolicyId() + ".xml");
205         LOGGER.info("Creating Policy {}", file.getAbsolutePath());
206         return XACMLPolicyWriter.writePolicyFile(file.toPath(), policy);
207     }
208
209     @Test
210     public void testUpdatingPolicies() {
211         assertThatCode(() -> {
212             //
213             // Just update root and policies
214             //
215             XacmlPolicyUtils.addPoliciesToXacmlRootPolicy(rootPolicy, policy1, policy2);
216             //
217             // Make sure it is correct
218             //
219             assertThat(rootPolicy.getPolicySetOrPolicyOrPolicySetIdReference()).hasSize(2);
220             //
221             // Save to disk
222             //
223             try (OutputStream os = new ByteArrayOutputStream()) {
224                 XACMLPolicyWriter.writePolicyFile(os, rootPolicy);
225                 LOGGER.debug("New Root Policy:{}{}", System.lineSeparator(), os.toString());
226             }
227             //
228             // Just update root and PolicySet
229             //
230             XacmlPolicyUtils.addPolicySetsToXacmlRootPolicy(rootPolicy, policySet5);
231             try (OutputStream os = new ByteArrayOutputStream()) {
232                 XACMLPolicyWriter.writePolicyFile(os, rootPolicy);
233                 LOGGER.debug("New Root Policy:{}{}", System.lineSeparator(), os.toString());
234             }
235         }).doesNotThrowAnyException();
236     }
237
238     @Test
239     public void testRemovingReferencedProperties() {
240         //
241         // Dump what we are starting with
242         //
243         XacmlPolicyUtils.debugDumpPolicyProperties(properties, LOGGER);
244         //
245         // Remove referenced policies
246         //
247         Path ref = Paths.get("src/test/resources/ref1.xml");
248         XacmlPolicyUtils.removeReferencedPolicy(properties, ref);
249         XacmlPolicyUtils.debugDumpPolicyProperties(properties, LOGGER);
250         assertThat(properties.getProperty("refstart1.file")).isNullOrEmpty();
251
252         ref = Paths.get("src/test/resources/ref2.xml");
253         XacmlPolicyUtils.removeReferencedPolicy(properties, ref);
254         XacmlPolicyUtils.debugDumpPolicyProperties(properties, LOGGER);
255         assertThat(properties.getProperty("refstart2.file")).isNullOrEmpty();
256
257         //
258         // Test one that isn't in there
259         //
260         ref = Paths.get("src/test/resources/NotThere.xml");
261         XacmlPolicyUtils.removeReferencedPolicy(properties, ref);
262         XacmlPolicyUtils.debugDumpPolicyProperties(properties, LOGGER);
263         assertThat(properties.getProperty("refstart3.file")).isNotBlank();
264
265         ref = Paths.get("src/test/resources/ref3.xml");
266         XacmlPolicyUtils.removeReferencedPolicy(properties, ref);
267         XacmlPolicyUtils.debugDumpPolicyProperties(properties, LOGGER);
268         assertThat(properties.getProperty("refstart3.file")).isNullOrEmpty();
269
270         ref = Paths.get("src/test/resources/ref4.xml");
271         XacmlPolicyUtils.removeReferencedPolicy(properties, ref);
272         XacmlPolicyUtils.debugDumpPolicyProperties(properties, LOGGER);
273         assertThat(properties.getProperty("refstart4.file")).isNullOrEmpty();
274     }
275
276     @Test
277     public void testRemovingRootProperties() {
278         //
279         // Dump what we are starting with
280         //
281         XacmlPolicyUtils.debugDumpPolicyProperties(properties, LOGGER);
282         //
283         // Remove root policies
284         //
285         Path ref = Paths.get("src/test/resources/root.xml");
286         XacmlPolicyUtils.removeRootPolicy(properties, ref);
287         XacmlPolicyUtils.debugDumpPolicyProperties(properties, LOGGER);
288         assertThat(properties.getProperty("root.file")).isNullOrEmpty();
289
290         //
291         // Test one that isn't in there
292         //
293         ref = Paths.get("src/test/resources/NotThere.xml");
294         XacmlPolicyUtils.removeRootPolicy(properties, ref);
295         XacmlPolicyUtils.debugDumpPolicyProperties(properties, LOGGER);
296         assertThat(properties.getProperty("refstart3.file")).isNotBlank();
297     }
298 }