2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 * SPDX-License-Identifier: Apache-2.0
20 * ============LICENSE_END=========================================================
23 package org.onap.policy.xacml.pdp.engine;
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;
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;
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;
51 import java.util.Map.Entry;
52 import java.util.Properties;
53 import java.util.ServiceLoader;
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;
65 public class OnapXacmlPdpEngineTest {
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;
73 public static final TemporaryFolder policyFolder = new TemporaryFolder();
76 * This is a simple annotation class to simulate
79 @XACMLRequest(ReturnPolicyIdList = true)
80 public class MyXacmlRequest {
82 @XACMLSubject(includeInResults = true)
83 String onapName = "DCAE";
85 @XACMLResource(includeInResults = true)
86 String resource = "onap.policies.Monitoring";
89 String action = "configure";
96 public static void setup() {
97 assertThatCode(() -> {
99 // Copy all the properties and root policies to the temporary folder
101 try (InputStream is = new FileInputStream("src/test/resources/xacml.properties")) {
106 propertiesFile = policyFolder.newFile("xacml.properties");
108 // Copy the root policies
110 for (String root : XACMLProperties.getRootPolicyIDs(properties)) {
114 Path rootPath = Paths.get(properties.getProperty(root + ".file"));
115 LOGGER.debug("Root file {} {}", rootPath, rootPath.getFileName());
117 // Construct new file name
119 File newRootPath = policyFolder.newFile(rootPath.getFileName().toString());
123 Files.copy(rootPath.toFile(), newRootPath);
124 assertThat(newRootPath).exists();
126 // Point to where the new policy is in the temp dir
128 properties.setProperty(root + ".file", newRootPath.getAbsolutePath());
130 try (OutputStream os = new FileOutputStream(propertiesFile.getAbsolutePath())) {
131 properties.store(os, "");
132 assertThat(propertiesFile).exists();
138 ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
139 ServiceLoader.load(XacmlApplicationServiceProvider.class);
141 // Iterate through them - I could store the object as
142 // XacmlApplicationServiceProvider pointer.
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());
155 LOGGER.debug("{}", strDump);
157 // Create the engine instance
159 onapPdpEngine = new OnapXacmlPdpEngine();
161 // Tell it to initialize based on the properties file
162 // we just built for it.
164 onapPdpEngine.initialize(propertiesFile.toPath().getParent());
166 // Make sure there's an application name
168 assertThat(onapPdpEngine.applicationName()).isNotEmpty();
170 // Ensure it has the supported policy types and
171 // can support the correct policy types.
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");
179 // Ensure it supports decisions
181 assertThat(onapPdpEngine.actionDecisionsSupported()).contains("configure");
182 }).doesNotThrowAnyException();
186 public void testNoPolicies() {
188 // Make a simple decision - NO policies are loaded
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());
196 }).doesNotThrowAnyException();
199 @SuppressWarnings("unchecked")
201 public void testvDnsPolicy() {
203 // Now load the vDNS Policy - make sure
204 // the pdp can support it and have it load
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");
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.
216 // In another future review....
218 for (Object policyObject : policies) {
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();
227 // Find the type and make sure the engine supports it
229 assertThat(policyDefinition.containsKey("type")).isTrue();
230 assertThat(onapPdpEngine.canSupportPolicyType(
231 policyDefinition.get("type").toString(),
232 policyDefinition.get("version").toString()))
237 // Just go ahead and load them all for now
239 // Assuming all are supported etc.
241 onapPdpEngine.loadPolicies(toscaObject);
243 //List<PolicyType> policies = onapPdpEngine.convertPolicies(is);
245 // Should have a policy
246 //// assertThat(policies.isEmpty()).isFalse();
248 }).doesNotThrowAnyException();
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);
258 }).withMessageContaining("missing metadata section");
260 assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> {
261 try (InputStream is =
262 new FileInputStream("src/test/resources/test.monitoring.policy.missingtype.yaml")) {
263 onapPdpEngine.convertPolicies(is);
265 }).withMessageContaining("missing type value");
267 assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> {
268 try (InputStream is =
269 new FileInputStream("src/test/resources/test.monitoring.policy.missingversion.yaml")) {
270 onapPdpEngine.convertPolicies(is);
272 }).withMessageContaining("missing version value");
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);
279 }).withMessageContaining("missing metadata policy-version");
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);
286 }).withMessageContaining("missing metadata policy-id");
288 assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> {
289 try (InputStream is =
290 new FileInputStream("src/test/resources/test.monitoring.policy.missingproperties.yaml")) {
291 onapPdpEngine.convertPolicies(is);
293 }).withMessageContaining("missing properties section");