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.application.guard;
25 import static org.assertj.core.api.Assertions.assertThat;
28 import java.io.FileInputStream;
29 import java.io.FileNotFoundException;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.util.HashMap;
33 import java.util.Iterator;
35 import java.util.Properties;
36 import java.util.ServiceLoader;
37 import java.util.UUID;
39 import org.junit.BeforeClass;
40 import org.junit.ClassRule;
41 import org.junit.FixMethodOrder;
42 import org.junit.Test;
43 import org.junit.rules.TemporaryFolder;
44 import org.junit.runners.MethodSorters;
45 import org.onap.policy.common.utils.coder.CoderException;
46 import org.onap.policy.common.utils.coder.StandardCoder;
47 import org.onap.policy.common.utils.resources.TextFileUtils;
48 import org.onap.policy.models.decisions.concepts.DecisionRequest;
49 import org.onap.policy.models.decisions.concepts.DecisionResponse;
50 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
51 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54 import org.yaml.snakeyaml.Yaml;
56 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
57 public class GuardPdpApplicationTest {
59 private static final Logger LOGGER = LoggerFactory.getLogger(GuardPdpApplicationTest.class);
60 private static Properties properties = new Properties();
61 private static File propertiesFile;
62 private static XacmlApplicationServiceProvider service;
63 private static DecisionRequest requestGuardPermit;
64 private static DecisionRequest requestGuardDeny;
65 private static DecisionRequest requestGuardDeny2;
66 private static StandardCoder gson = new StandardCoder();
69 public static final TemporaryFolder policyFolder = new TemporaryFolder();
72 * Copies the xacml.properties and policies files into
73 * temporary folder and loads the service provider saving
74 * instance of provider off for other tests to use.
77 public static void setUp() throws Exception {
79 // Setup our temporary folder
81 XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
82 propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
83 properties, myCreator);
87 ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
88 ServiceLoader.load(XacmlApplicationServiceProvider.class);
90 // Find the guard service application and save for use in all the tests
92 StringBuilder strDump = new StringBuilder("Loaded applications:" + System.lineSeparator());
93 Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
94 while (iterator.hasNext()) {
95 XacmlApplicationServiceProvider application = iterator.next();
99 if (application instanceof GuardPdpApplication) {
101 // Should be the first and only one
103 assertThat(service).isNull();
104 service = application;
106 strDump.append(application.applicationName());
107 strDump.append(" supports ");
108 strDump.append(application.supportedPolicyTypes());
109 strDump.append(System.lineSeparator());
111 LOGGER.debug("{}", strDump);
113 // Tell it to initialize based on the properties file
114 // we just built for it.
116 service.initialize(propertiesFile.toPath().getParent());
120 public void test1Basics() throws CoderException, IOException {
122 // Load Single Decision Request
124 requestGuardPermit = gson.decode(
125 TextFileUtils.getTextFileAsString(
126 "../../main/src/test/resources/decisions/decision.guard.shouldpermit.input.json"),
127 DecisionRequest.class);
129 // Load Single Decision Request
131 requestGuardDeny = gson.decode(TextFileUtils.getTextFileAsString(
132 "../../main/src/test/resources/decisions/decision.guard.shoulddeny.input.json"),
133 DecisionRequest.class);
135 // Load Single Decision Request
137 requestGuardDeny2 = gson.decode(TextFileUtils.getTextFileAsString(
138 "../../main/src/test/resources/decisions/decision.guard.shoulddeny.input2.json"),
139 DecisionRequest.class);
141 // Make sure there's an application name
143 assertThat(service.applicationName()).isNotEmpty();
147 assertThat(service.actionDecisionsSupported().size()).isEqualTo(1);
148 assertThat(service.actionDecisionsSupported()).contains("guard");
150 // Ensure it has the supported policy types and
151 // can support the correct policy types.
153 assertThat(service.supportedPolicyTypes()).isNotEmpty();
154 assertThat(service.supportedPolicyTypes().size()).isEqualTo(2);
155 assertThat(service.canSupportPolicyType("onap.policies.controlloop.guard.FrequencyLimiter", "1.0.0"))
157 assertThat(service.canSupportPolicyType("onap.policies.controlloop.guard.FrequencyLimiter", "1.0.1"))
159 assertThat(service.canSupportPolicyType("onap.policies.controlloop.guard.MinMax", "1.0.0")).isTrue();
160 assertThat(service.canSupportPolicyType("onap.policies.controlloop.guard.MinMax", "1.0.1")).isFalse();
161 assertThat(service.canSupportPolicyType("onap.foo", "1.0.1")).isFalse();
165 public void test2NoPolicies() {
167 // Ask for a decision
169 DecisionResponse response = service.makeDecision(requestGuardPermit);
170 LOGGER.info("Decision {}", response);
172 assertThat(response).isNotNull();
173 assertThat(response.getStatus()).isEqualTo("Permit");
177 public void test3FrequencyLimiter() throws CoderException, FileNotFoundException, IOException {
179 // Now load the vDNS frequency limiter Policy - make sure
180 // the pdp can support it and have it load
183 try (InputStream is = new FileInputStream("src/test/resources/vDNS.policy.guard.frequency.output.tosca.yaml")) {
185 // Have yaml parse it
187 Yaml yaml = new Yaml();
188 Map<String, Object> toscaObject = yaml.load(is);
192 service.loadPolicies(toscaObject);
194 // Ask for a decision - should get permit
196 DecisionResponse response = service.makeDecision(requestGuardPermit);
197 LOGGER.info("Looking for Permit Decision {}", response);
199 assertThat(response).isNotNull();
200 assertThat(response.getStatus()).isNotNull();
201 assertThat(response.getStatus()).isEqualTo("Permit");
203 // Dump it out as Json
205 LOGGER.info(gson.encode(response));
207 // Ask for a decision - should get deny
209 response = service.makeDecision(requestGuardDeny2);
210 LOGGER.info("Looking for Deny Decision {}", response);
211 assertThat(response).isNotNull();
212 assertThat(response.getStatus()).isNotNull();
213 assertThat(response.getStatus()).isEqualTo("Deny");
215 // Dump it out as Json
217 LOGGER.info(gson.encode(response));
222 public void test4MinMax() throws CoderException, FileNotFoundException, IOException {
224 // Now load the vDNS min max Policy - make sure
225 // the pdp can support it and have it load
228 try (InputStream is = new FileInputStream("src/test/resources/vDNS.policy.guard.minmax.output.tosca.yaml")) {
230 // Have yaml parse it
232 Yaml yaml = new Yaml();
233 Map<String, Object> toscaObject = yaml.load(is);
237 service.loadPolicies(toscaObject);
239 // Ask for a decision - should get permit
241 DecisionResponse response = service.makeDecision(requestGuardPermit);
242 LOGGER.info("Looking for Permit Decision {}", response);
244 assertThat(response).isNotNull();
245 assertThat(response.getStatus()).isNotNull();
246 assertThat(response.getStatus()).isEqualTo("Permit");
248 // Dump it out as Json
250 LOGGER.info(gson.encode(response));
252 // Ask for a decision - should get deny
254 response = service.makeDecision(requestGuardDeny);
255 LOGGER.info("Looking for Deny Decision {}", response);
256 assertThat(response).isNotNull();
257 assertThat(response.getStatus()).isNotNull();
258 assertThat(response.getStatus()).isEqualTo("Deny");
260 // Dump it out as Json
262 LOGGER.info(gson.encode(response));
267 public void test5MissingFields() throws FileNotFoundException, IOException {
268 LOGGER.debug("Running test5");
270 // Most likely we would not get a policy with missing fields passed to
271 // us from the API. But in case that happens, or we decide that some fields
272 // will be optional due to re-working of how the XACML policies are built,
273 // let's add support in for that.
275 try (InputStream is = new FileInputStream("src/test/resources/guard.policy-minmax-missing-fields1.yaml")) {
277 // Have yaml parse it
279 Yaml yaml = new Yaml();
280 Map<String, Object> toscaObject = yaml.load(is);
284 service.loadPolicies(toscaObject);
286 // We can create a DecisionRequest on the fly - no need
287 // to have it in the .json files
289 DecisionRequest request = new DecisionRequest();
290 request.setOnapName("JUnit");
291 request.setOnapComponent("test5MissingFields");
292 request.setRequestId(UUID.randomUUID().toString());
293 request.setAction("guard");
294 Map<String, Object> guard = new HashMap<>();
295 guard.put("actor", "FOO");
296 guard.put("recipe", "bar");
297 guard.put("vfCount", "4");
298 Map<String, Object> resource = new HashMap<>();
299 resource.put("guard", guard);
300 request.setResource(resource);
302 // Ask for a decision - should get permit
304 DecisionResponse response = service.makeDecision(request);
305 LOGGER.info("Looking for Permit Decision {}", response);
306 assertThat(response).isNotNull();
307 assertThat(response.getStatus()).isNotNull();
308 assertThat(response.getStatus()).isEqualTo("Permit");
312 guard.put("vfCount", "10");
313 resource.put("guard", guard);
314 request.setResource(resource);
315 response = service.makeDecision(request);
316 LOGGER.info("Looking for Deny Decision {}", response);
317 assertThat(response).isNotNull();
318 assertThat(response.getStatus()).isNotNull();
319 assertThat(response.getStatus()).isEqualTo("Deny");