ed63bb9c4d8c072769186073c5a14cc30e467bd7
[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.Properties;
41
42 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
43 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
50
51 import org.junit.BeforeClass;
52 import org.junit.ClassRule;
53 import org.junit.Test;
54 import org.junit.rules.TemporaryFolder;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 /**
59  * Utility methods for storing policies to disk and updating Properties objects
60  * that reference policies.
61  *
62  * @author pameladragosh
63  *
64  */
65 public class XacmlPolicyUtilsTest {
66     private static final Logger LOGGER = LoggerFactory.getLogger(XacmlPolicyUtilsTest.class);
67
68     static Properties properties;
69
70     static PolicySetType rootPolicy = XacmlPolicyUtils.createEmptyPolicySet("root", XACML3.ID_POLICY_FIRST_APPLICABLE);
71
72     static Path rootPath;
73
74     static PolicyType policy1 = XacmlPolicyUtils.createEmptyPolicy("policy1", XACML3.ID_RULE_DENY_UNLESS_PERMIT);
75     static PolicyType policy2 = XacmlPolicyUtils.createEmptyPolicy("policy2", XACML3.ID_RULE_DENY_UNLESS_PERMIT);
76     static PolicyType policy3 = XacmlPolicyUtils.createEmptyPolicy("policy3", XACML3.ID_RULE_DENY_UNLESS_PERMIT);
77     static PolicyType policy4 = XacmlPolicyUtils.createEmptyPolicy("policy4", XACML3.ID_RULE_DENY_UNLESS_PERMIT);
78
79     static PolicySetType policySet5 = XacmlPolicyUtils.createEmptyPolicySet(
80             "policyset1", XACML3.ID_POLICY_FIRST_APPLICABLE);
81
82     static Path path1;
83     static Path path2;
84     static Path path3;
85     static Path path4;
86
87     static Path policySetPath;
88
89     /**
90      * Temporary folder where we will store newly created policies.
91      */
92     @ClassRule
93     public static TemporaryFolder policyFolder = new TemporaryFolder();
94
95     /**
96      * Setup the JUnit tests by finishing creating the policies and
97      * writing them out to the temporary folder.
98      *
99      * @throws Exception thrown
100      */
101     @BeforeClass
102     public static void setUp() throws Exception {
103         assertThatCode(() -> {
104             //
105             // Load our test property object
106             //
107             try (InputStream is = new FileInputStream("src/test/resources/test.properties")) {
108                 properties = new Properties();
109                 properties.load(is);
110             }
111             //
112             // Save root policy
113             //
114             File rootFile = policyFolder.newFile("root.xml");
115             LOGGER.info("Creating Root Policy {}", rootFile.getAbsolutePath());
116             rootPath = XACMLPolicyWriter.writePolicyFile(rootFile.toPath(), rootPolicy);
117             //
118             // Create policies - Policies 1 and 2 will become references in the
119             // root policy. While Policies 3 and 4 will become references in the
120             // soon to be created PolicySet 5 below.
121             //
122             path1 = createPolicyContents(policy1, "resource1");
123             LOGGER.info(new String(Files.readAllBytes(path1)));
124             path2 = createPolicyContents(policy2, "resource2");
125             LOGGER.info(new String(Files.readAllBytes(path2)));
126             path3 = createPolicyContents(policy3, "resourc31");
127             LOGGER.info(new String(Files.readAllBytes(path3)));
128             path4 = createPolicyContents(policy4, "resource4");
129             LOGGER.info(new String(Files.readAllBytes(path4)));
130             //
131             // Create our PolicySet
132             //
133             policySet5.setPolicySetId("policyset5");
134             policySet5.setTarget(new TargetType());
135             policySet5.setPolicyCombiningAlgId(XACML3.ID_POLICY_FIRST_APPLICABLE.stringValue());
136             ObjectFactory factory = new ObjectFactory();
137             //
138             // Add Policies 3 and 4 to the PolicySet
139             //
140             policySet5.getPolicySetOrPolicyOrPolicySetIdReference().add(factory.createPolicy(policy1));
141             policySet5.getPolicySetOrPolicyOrPolicySetIdReference().add(factory.createPolicy(policy2));
142             assertThat(policySet5.getPolicySetOrPolicyOrPolicySetIdReference()).hasSize(2);
143             //
144             // Save that to disk
145             //
146             File policySetFile = policyFolder.newFile("policySet5.xml");
147             LOGGER.info("Creating PolicySet {}", policySetFile.getAbsolutePath());
148             policySetPath = XACMLPolicyWriter.writePolicyFile(policySetFile.toPath(), policySet5);
149
150         }).doesNotThrowAnyException();
151     }
152
153     /**
154      * Helper method that creates a very simple Policy and Rule and saves it to disk.
155      *
156      * @param policy Policy to store contents in
157      * @param resource A simple resource id for the Target
158      * @return Path object of the policy
159      * @throws IOException If unable to write to disk
160      */
161     private static Path createPolicyContents(PolicyType policy, String resource) throws IOException {
162         //
163         // Create The Match
164         //
165         MatchType matchPolicyId = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
166                 XACML3.ID_FUNCTION_STRING_EQUAL,
167                 resource,
168                 XACML3.ID_DATATYPE_STRING,
169                 XACML3.ID_RESOURCE_RESOURCE_ID,
170                 XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);
171         //
172         // This is our outer AnyOf - which is an OR
173         //
174         AnyOfType anyOf = new AnyOfType();
175         //
176         // Create AllOf (AND) of just Policy Id
177         //
178         anyOf.getAllOf().add(ToscaPolicyTranslatorUtils.buildAllOf(matchPolicyId));
179         TargetType target = new TargetType();
180         target.getAnyOf().add(anyOf);
181         policy.setTarget(target);
182         RuleType rule = new RuleType();
183         rule.setRuleId(policy.getPolicyId() + ":rule");
184         rule.setEffect(EffectType.PERMIT);
185         rule.setTarget(new TargetType());
186         //
187         // Add the rule to the policy
188         //
189         policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
190         //
191         // Save it to disk
192         //
193         File file = policyFolder.newFile(policy.getPolicyId() + ".xml");
194         LOGGER.info("Creating Policy {}", file.getAbsolutePath());
195         return XACMLPolicyWriter.writePolicyFile(file.toPath(), policy);
196     }
197
198     @Test
199     public void testUpdatingPolicies() {
200         assertThatCode(() -> {
201             //
202             // Just update root and policies
203             //
204             XacmlPolicyUtils.addPoliciesToXacmlRootPolicy(rootPolicy, policy1, policy2);
205             //
206             // Make sure it is correct
207             //
208             assertThat(rootPolicy.getPolicySetOrPolicyOrPolicySetIdReference()).hasSize(2);
209             //
210             // Save to disk
211             //
212             try (OutputStream os = new ByteArrayOutputStream()) {
213                 XACMLPolicyWriter.writePolicyFile(os, rootPolicy);
214                 LOGGER.debug("New Root Policy:{}{}", System.lineSeparator(), os.toString());
215             }
216             //
217             // Just update root and PolicySet
218             //
219             XacmlPolicyUtils.addPolicySetsToXacmlRootPolicy(rootPolicy, policySet5);
220             try (OutputStream os = new ByteArrayOutputStream()) {
221                 XACMLPolicyWriter.writePolicyFile(os, rootPolicy);
222                 LOGGER.debug("New Root Policy:{}{}", System.lineSeparator(), os.toString());
223             }
224         }).doesNotThrowAnyException();
225     }
226
227     @Test
228     public void testRemovingReferencedProperties() {
229         //
230         // Dump what we are starting with
231         //
232         XacmlPolicyUtils.debugDumpPolicyProperties(properties, LOGGER);
233         //
234         // Remove referenced policies
235         //
236         Path ref = Paths.get("src/test/resources/ref1.xml");
237         XacmlPolicyUtils.removeReferencedPolicy(properties, ref);
238         XacmlPolicyUtils.debugDumpPolicyProperties(properties, LOGGER);
239         assertThat(properties.getProperty("refstart1.file")).isNullOrEmpty();
240
241         ref = Paths.get("src/test/resources/ref2.xml");
242         XacmlPolicyUtils.removeReferencedPolicy(properties, ref);
243         XacmlPolicyUtils.debugDumpPolicyProperties(properties, LOGGER);
244         assertThat(properties.getProperty("refstart2.file")).isNullOrEmpty();
245
246         //
247         // Test one that isn't in there
248         //
249         ref = Paths.get("src/test/resources/NotThere.xml");
250         XacmlPolicyUtils.removeReferencedPolicy(properties, ref);
251         XacmlPolicyUtils.debugDumpPolicyProperties(properties, LOGGER);
252         assertThat(properties.getProperty("refstart3.file")).isNotBlank();
253
254         ref = Paths.get("src/test/resources/ref3.xml");
255         XacmlPolicyUtils.removeReferencedPolicy(properties, ref);
256         XacmlPolicyUtils.debugDumpPolicyProperties(properties, LOGGER);
257         assertThat(properties.getProperty("refstart3.file")).isNullOrEmpty();
258
259         ref = Paths.get("src/test/resources/ref4.xml");
260         XacmlPolicyUtils.removeReferencedPolicy(properties, ref);
261         XacmlPolicyUtils.debugDumpPolicyProperties(properties, LOGGER);
262         assertThat(properties.getProperty("refstart4.file")).isNullOrEmpty();
263     }
264
265     @Test
266     public void testRemovingRootProperties() {
267         //
268         // Dump what we are starting with
269         //
270         XacmlPolicyUtils.debugDumpPolicyProperties(properties, LOGGER);
271         //
272         // Remove root policies
273         //
274         Path ref = Paths.get("src/test/resources/root.xml");
275         XacmlPolicyUtils.removeRootPolicy(properties, ref);
276         XacmlPolicyUtils.debugDumpPolicyProperties(properties, LOGGER);
277         assertThat(properties.getProperty("root.file")).isNullOrEmpty();
278
279         //
280         // Test one that isn't in there
281         //
282         ref = Paths.get("src/test/resources/NotThere.xml");
283         XacmlPolicyUtils.removeRootPolicy(properties, ref);
284         XacmlPolicyUtils.debugDumpPolicyProperties(properties, LOGGER);
285         assertThat(properties.getProperty("refstart3.file")).isNotBlank();
286     }
287 }