940a974b196ed8e2da242c776a06007093f94acf
[policy/xacml-pdp.git] / applications / monitoring / src / test / java / org / onap / policy / xacml / pdp / engine / OnapXacmlPdpEngineTest.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.xacml.pdp.engine;
24
25 import static org.assertj.core.api.Assertions.assertThat;
26 import static org.assertj.core.api.Assertions.assertThatCode;
27 import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
28 import static org.junit.Assert.assertEquals;
29
30 import com.att.research.xacml.api.Decision;
31 import com.att.research.xacml.api.Response;
32 import com.att.research.xacml.api.Result;
33 import com.att.research.xacml.std.annotations.RequestParser;
34 import com.att.research.xacml.std.annotations.XACMLAction;
35 import com.att.research.xacml.std.annotations.XACMLRequest;
36 import com.att.research.xacml.std.annotations.XACMLResource;
37 import com.att.research.xacml.std.annotations.XACMLSubject;
38 import com.att.research.xacml.util.XACMLProperties;
39 import com.google.common.io.Files;
40
41 import java.io.File;
42 import java.io.FileInputStream;
43 import java.io.FileOutputStream;
44 import java.io.InputStream;
45 import java.io.OutputStream;
46 import java.nio.file.Path;
47 import java.nio.file.Paths;
48 import java.util.Iterator;
49 import java.util.List;
50 import java.util.Map;
51 import java.util.Map.Entry;
52 import java.util.Properties;
53 import java.util.ServiceLoader;
54
55 import org.junit.BeforeClass;
56 import org.junit.ClassRule;
57 import org.junit.Test;
58 import org.junit.rules.TemporaryFolder;
59 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
60 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
63 import org.yaml.snakeyaml.Yaml;
64
65 public class OnapXacmlPdpEngineTest {
66
67     private static final Logger LOGGER = LoggerFactory.getLogger(OnapXacmlPdpEngineTest.class);
68     private static OnapXacmlPdpEngine onapPdpEngine;
69     private static Properties properties = new Properties();
70     private static File propertiesFile;
71
72     @ClassRule
73     public static final TemporaryFolder policyFolder = new TemporaryFolder();
74
75     /**
76      * This is a simple annotation class to simulate
77      * requests coming in.
78      */
79     @XACMLRequest(ReturnPolicyIdList = true)
80     public class MyXacmlRequest {
81
82         @XACMLSubject(includeInResults = true)
83         String onapName = "DCAE";
84
85         @XACMLResource(includeInResults = true)
86         String resource = "onap.policies.Monitoring";
87
88         @XACMLAction()
89         String action = "configure";
90     }
91
92     /**
93      * Load a test engine.
94      */
95     @BeforeClass
96     public static void setup() {
97         assertThatCode(() -> {
98             //
99             // Copy all the properties and root policies to the temporary folder
100             //
101             try (InputStream is = new FileInputStream("src/test/resources/xacml.properties")) {
102                 //
103                 // Load it in
104                 //
105                 properties.load(is);
106                 propertiesFile = policyFolder.newFile("xacml.properties");
107                 //
108                 // Copy the root policies
109                 //
110                 for (String root : XACMLProperties.getRootPolicyIDs(properties)) {
111                     //
112                     // Get a file
113                     //
114                     Path rootPath = Paths.get(properties.getProperty(root + ".file"));
115                     LOGGER.debug("Root file {} {}", rootPath, rootPath.getFileName());
116                     //
117                     // Construct new file name
118                     //
119                     File newRootPath = policyFolder.newFile(rootPath.getFileName().toString());
120                     //
121                     // Copy it
122                     //
123                     Files.copy(rootPath.toFile(), newRootPath);
124                     assertThat(newRootPath).exists();
125                     //
126                     // Point to where the new policy is in the temp dir
127                     //
128                     properties.setProperty(root + ".file", newRootPath.getAbsolutePath());
129                 }
130                 try (OutputStream os = new FileOutputStream(propertiesFile.getAbsolutePath())) {
131                     properties.store(os, "");
132                     assertThat(propertiesFile).exists();
133                 }
134             }
135             //
136             // Load service
137             //
138             ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
139                     ServiceLoader.load(XacmlApplicationServiceProvider.class);
140             //
141             // Iterate through them - I could store the object as
142             // XacmlApplicationServiceProvider pointer.
143             //
144             // Try this later.
145             //
146             StringBuilder strDump = new StringBuilder("Loaded applications:" + System.lineSeparator());
147             Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
148             while (iterator.hasNext()) {
149                 XacmlApplicationServiceProvider application = iterator.next();
150                 strDump.append(application.applicationName());
151                 strDump.append(" supports ");
152                 strDump.append(application.supportedPolicyTypes());
153                 strDump.append(System.lineSeparator());
154             }
155             LOGGER.debug("{}", strDump);
156             //
157             // Create the engine instance
158             //
159             onapPdpEngine = new OnapXacmlPdpEngine();
160             //
161             // Tell it to initialize based on the properties file
162             // we just built for it.
163             //
164             onapPdpEngine.initialize(propertiesFile.toPath().getParent());
165             //
166             // Make sure there's an application name
167             //
168             assertThat(onapPdpEngine.applicationName()).isNotEmpty();
169             //
170             // Ensure it has the supported policy types and
171             // can support the correct policy types.
172             //
173             assertThat(onapPdpEngine.canSupportPolicyType("onap.Monitoring", "1.0.0")).isTrue();
174             assertThat(onapPdpEngine.canSupportPolicyType("onap.Monitoring", "1.5.0")).isTrue();
175             assertThat(onapPdpEngine.canSupportPolicyType("onap.policies.monitoring.foobar", "1.0.1")).isTrue();
176             assertThat(onapPdpEngine.canSupportPolicyType("onap.foobar", "1.0.0")).isFalse();
177             assertThat(onapPdpEngine.supportedPolicyTypes()).contains("onap.Monitoring");
178             //
179             // Ensure it supports decisions
180             //
181             assertThat(onapPdpEngine.actionDecisionsSupported()).contains("configure");
182         }).doesNotThrowAnyException();
183     }
184
185     @Test
186     public void testNoPolicies() {
187         //
188         // Make a simple decision - NO policies are loaded
189         //
190         assertThatCode(() -> {
191             Response response = onapPdpEngine.decision(RequestParser.parseRequest(new MyXacmlRequest()));
192             for (Result result : response.getResults()) {
193                 LOGGER.info("Decision {}", result.getDecision());
194                 assertEquals(Decision.PERMIT, result.getDecision());
195             }
196         }).doesNotThrowAnyException();
197     }
198
199     @SuppressWarnings("unchecked")
200     @Test
201     public void testvDnsPolicy() {
202         //
203         // Now load the vDNS Policy - make sure
204         // the pdp can support it and have it load
205         // into the PDP.
206         //
207         assertThatCode(() -> {
208             try (InputStream is = new FileInputStream("src/test/resources/vDNS.policy.input.yaml")) {
209                 Yaml yaml = new Yaml();
210                 Map<String, Object> toscaObject = yaml.load(is);
211                 List<Object> policies = (List<Object>) toscaObject.get("policies");
212                 //
213                 // What we should really do is split the policies out from the ones that
214                 // are not supported to ones that are. And then load these.
215                 //
216                 // In another future review....
217                 //
218                 for (Object policyObject : policies) {
219                     //
220                     // Get the contents
221                     //
222                     Map<String, Object> policyContents = (Map<String, Object>) policyObject;
223                     for (Entry<String, Object> entrySet : policyContents.entrySet()) {
224                         LOGGER.info("Entry set {}", entrySet.getKey());
225                         Map<String, Object> policyDefinition = (Map<String, Object>) entrySet.getValue();
226                         //
227                         // Find the type and make sure the engine supports it
228                         //
229                         assertThat(policyDefinition.containsKey("type")).isTrue();
230                         assertThat(onapPdpEngine.canSupportPolicyType(
231                                 policyDefinition.get("type").toString(),
232                                 policyDefinition.get("version").toString()))
233                             .isTrue();
234                     }
235                 }
236                 //
237                 // Just go ahead and load them all for now
238                 //
239                 // Assuming all are supported etc.
240                 //
241                 onapPdpEngine.loadPolicies(toscaObject);
242
243                 //List<PolicyType> policies = onapPdpEngine.convertPolicies(is);
244                 //
245                 // Should have a policy
246                 ////                assertThat(policies.isEmpty()).isFalse();
247             }
248         }).doesNotThrowAnyException();
249     }
250
251     @Test
252     public void testBadPolicies() {
253         assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> {
254             try (InputStream is =
255                     new FileInputStream("src/test/resources/test.monitoring.policy.missingmetadata.yaml")) {
256                 onapPdpEngine.convertPolicies(is);
257             }
258         }).withMessageContaining("missing metadata section");
259
260         assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> {
261             try (InputStream is =
262                     new FileInputStream("src/test/resources/test.monitoring.policy.missingtype.yaml")) {
263                 onapPdpEngine.convertPolicies(is);
264             }
265         }).withMessageContaining("missing type value");
266
267         assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> {
268             try (InputStream is =
269                     new FileInputStream("src/test/resources/test.monitoring.policy.missingversion.yaml")) {
270                 onapPdpEngine.convertPolicies(is);
271             }
272         }).withMessageContaining("missing version value");
273
274         assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> {
275             try (InputStream is =
276                     new FileInputStream("src/test/resources/test.monitoring.policy.badmetadata.1.yaml")) {
277                 onapPdpEngine.convertPolicies(is);
278             }
279         }).withMessageContaining("missing metadata policy-version");
280
281         assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> {
282             try (InputStream is =
283                     new FileInputStream("src/test/resources/test.monitoring.policy.badmetadata.2.yaml")) {
284                 onapPdpEngine.convertPolicies(is);
285             }
286         }).withMessageContaining("missing metadata policy-id");
287
288         assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> {
289             try (InputStream is =
290                     new FileInputStream("src/test/resources/test.monitoring.policy.missingproperties.yaml")) {
291                 onapPdpEngine.convertPolicies(is);
292             }
293         }).withMessageContaining("missing properties section");
294     }
295
296 }