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;
33 import java.time.Instant;
34 import java.util.HashMap;
35 import java.util.Iterator;
37 import java.util.Properties;
38 import java.util.ServiceLoader;
39 import java.util.UUID;
41 import javax.persistence.EntityManager;
42 import javax.persistence.Persistence;
44 import org.junit.AfterClass;
45 import org.junit.Before;
46 import org.junit.BeforeClass;
47 import org.junit.ClassRule;
48 import org.junit.FixMethodOrder;
49 import org.junit.Test;
50 import org.junit.rules.TemporaryFolder;
51 import org.junit.runners.MethodSorters;
52 import org.onap.policy.common.utils.coder.CoderException;
53 import org.onap.policy.common.utils.coder.StandardCoder;
54 import org.onap.policy.common.utils.resources.TextFileUtils;
55 import org.onap.policy.models.decisions.concepts.DecisionRequest;
56 import org.onap.policy.models.decisions.concepts.DecisionResponse;
57 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
58 import org.onap.policy.pdp.xacml.application.common.OnapOperationsHistoryDbao;
59 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
60 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
61 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
64 import org.yaml.snakeyaml.Yaml;
66 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
67 public class GuardPdpApplicationTest {
69 private static final Logger LOGGER = LoggerFactory.getLogger(GuardPdpApplicationTest.class);
70 private static Properties properties = new Properties();
71 private static File propertiesFile;
72 private static XacmlApplicationServiceProvider service;
73 private static DecisionRequest requestVfCount1;
74 private static DecisionRequest requestVfCount3;
75 private static DecisionRequest requestVfCount6;
76 private static StandardCoder gson = new StandardCoder();
77 private static EntityManager em;
78 private static final String DENY = "Deny";
79 private static final String PERMIT = "Permit";
82 public static final TemporaryFolder policyFolder = new TemporaryFolder();
85 * Copies the xacml.properties and policies files into
86 * temporary folder and loads the service provider saving
87 * instance of provider off for other tests to use.
90 public static void setUp() throws Exception {
91 LOGGER.info("Setting up class");
93 // Setup our temporary folder
95 XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
96 propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
97 properties, myCreator);
101 ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
102 ServiceLoader.load(XacmlApplicationServiceProvider.class);
104 // Find the guard service application and save for use in all the tests
106 StringBuilder strDump = new StringBuilder("Loaded applications:" + System.lineSeparator());
107 Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
108 while (iterator.hasNext()) {
109 XacmlApplicationServiceProvider application = iterator.next();
111 // Is it our service?
113 if (application instanceof GuardPdpApplication) {
115 // Should be the first and only one
117 assertThat(service).isNull();
118 service = application;
120 strDump.append(application.applicationName());
121 strDump.append(" supports ");
122 strDump.append(application.supportedPolicyTypes());
123 strDump.append(System.lineSeparator());
125 LOGGER.info("{}", strDump);
127 // Tell it to initialize based on the properties file
128 // we just built for it.
130 service.initialize(propertiesFile.toPath().getParent());
132 // Load Decision Requests
134 requestVfCount1 = gson.decode(
135 TextFileUtils.getTextFileAsString(
136 "../../main/src/test/resources/decisions/decision.guard.vfCount.1.input.json"),
137 DecisionRequest.class);
138 requestVfCount3 = gson.decode(
139 TextFileUtils.getTextFileAsString(
140 "../../main/src/test/resources/decisions/decision.guard.vfCount.3.input.json"),
141 DecisionRequest.class);
142 requestVfCount6 = gson.decode(
143 TextFileUtils.getTextFileAsString(
144 "../../main/src/test/resources/decisions/decision.guard.vfCount.6.input.json"),
145 DecisionRequest.class);
147 // Create EntityManager for manipulating DB
149 em = Persistence.createEntityManagerFactory(
150 GuardPdpApplicationTest.properties.getProperty("historydb.persistenceunit"), properties)
151 .createEntityManager();
155 * Clears the database before each test.
159 public void startClean() throws Exception {
160 em.getTransaction().begin();
161 em.createQuery("DELETE FROM OnapOperationsHistoryDbao").executeUpdate();
162 em.getTransaction().commit();
166 * Check that decision matches expectation.
168 * @param expected from the response
169 * @param response received
172 public void checkDecision(String expected, DecisionResponse response) throws CoderException {
173 LOGGER.info("Looking for {} Decision", expected);
174 assertThat(response).isNotNull();
175 assertThat(response.getStatus()).isNotNull();
176 assertThat(response.getStatus()).isEqualTo(expected);
178 // Dump it out as Json
180 LOGGER.info(gson.encode(response));
184 * Request a decision and check that it matches expectation.
186 * @param request to send to Xacml PDP
187 * @param expected from the response
190 public void requestAndCheckDecision(DecisionRequest request, String expected) throws CoderException {
192 // Ask for a decision
194 DecisionResponse response = service.makeDecision(request);
198 checkDecision(expected, response);
202 public void test1Basics() throws CoderException, IOException {
203 LOGGER.info("**************** Running test1 ****************");
205 // Make sure there's an application name
207 assertThat(service.applicationName()).isNotEmpty();
211 assertThat(service.actionDecisionsSupported().size()).isEqualTo(1);
212 assertThat(service.actionDecisionsSupported()).contains("guard");
214 // Ensure it has the supported policy types and
215 // can support the correct policy types.
217 assertThat(service.supportedPolicyTypes()).isNotEmpty();
218 assertThat(service.supportedPolicyTypes().size()).isEqualTo(2);
219 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
220 "onap.policies.controlloop.guard.FrequencyLimiter", "1.0.0"))).isTrue();
221 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
222 "onap.policies.controlloop.guard.FrequencyLimiter", "1.0.1"))).isFalse();
223 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
224 "onap.policies.controlloop.guard.MinMax", "1.0.0"))).isTrue();
225 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
226 "onap.policies.controlloop.guard.MinMax", "1.0.1"))).isFalse();
227 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier("onap.foo", "1.0.1"))).isFalse();
231 public void test2NoPolicies() throws CoderException {
232 LOGGER.info("**************** Running test2 ****************");
233 requestAndCheckDecision(requestVfCount1,PERMIT);
237 public void test3FrequencyLimiter() throws CoderException, FileNotFoundException, IOException,
238 XacmlApplicationException {
239 LOGGER.info("**************** Running test3 ****************");
241 // Now load the vDNS frequency limiter Policy - make sure
242 // the pdp can support it and have it load
245 try (InputStream is = new FileInputStream("src/test/resources/vDNS.policy.guard.frequency.output.tosca.yaml")) {
247 // Have yaml parse it
249 Yaml yaml = new Yaml();
250 Map<String, Object> toscaObject = yaml.load(is);
254 service.loadPolicies(toscaObject);
257 // Zero recent actions: should get permit
259 requestAndCheckDecision(requestVfCount1,PERMIT);
261 // Add entry into operations history DB
263 insertOperationEvent(requestVfCount1);
265 // Only one recent actions: should get permit
267 requestAndCheckDecision(requestVfCount1,PERMIT);
269 // Add entry into operations history DB
271 insertOperationEvent(requestVfCount1);
273 // Two recent actions, more than specified limit of 2: should get deny
275 requestAndCheckDecision(requestVfCount1,DENY);
279 public void test4MinMax() throws CoderException, FileNotFoundException, IOException, XacmlApplicationException {
280 LOGGER.info("**************** Running test4 ****************");
282 // Now load the vDNS min max Policy - make sure
283 // the pdp can support it and have it load
286 try (InputStream is = new FileInputStream("src/test/resources/vDNS.policy.guard.minmax.output.tosca.yaml")) {
288 // Have yaml parse it
290 Yaml yaml = new Yaml();
291 Map<String, Object> toscaObject = yaml.load(is);
295 service.loadPolicies(toscaObject);
298 // vfcount=1 below min of 2: should get a Deny
300 requestAndCheckDecision(requestVfCount1, DENY);
302 // vfcount=3 between min of 2 and max of 5: should get a Permit
304 requestAndCheckDecision(requestVfCount3, PERMIT);
306 // vfcount=6 above max of 5: should get a Deny
308 requestAndCheckDecision(requestVfCount6,DENY);
310 // Add two entry into operations history DB
312 insertOperationEvent(requestVfCount1);
313 insertOperationEvent(requestVfCount1);
315 // vfcount=3 between min of 2 and max of 5, but 2 recent actions is above frequency limit: should get a Deny
317 requestAndCheckDecision(requestVfCount3, DENY);
319 // vfcount=6 above max of 5: should get a Deny
321 requestAndCheckDecision(requestVfCount6, DENY);
325 public void test5MissingFields() throws FileNotFoundException, IOException, XacmlApplicationException {
326 LOGGER.info("**************** Running test5 ****************");
328 // Most likely we would not get a policy with missing fields passed to
329 // us from the API. But in case that happens, or we decide that some fields
330 // will be optional due to re-working of how the XACML policies are built,
331 // let's add support in for that.
333 try (InputStream is = new FileInputStream("src/test/resources/guard.policy-minmax-missing-fields1.yaml")) {
335 // Have yaml parse it
337 Yaml yaml = new Yaml();
338 Map<String, Object> toscaObject = yaml.load(is);
342 service.loadPolicies(toscaObject);
344 // We can create a DecisionRequest on the fly - no need
345 // to have it in the .json files
347 DecisionRequest request = new DecisionRequest();
348 request.setOnapName("JUnit");
349 request.setOnapComponent("test5MissingFields");
350 request.setRequestId(UUID.randomUUID().toString());
351 request.setAction("guard");
352 Map<String, Object> guard = new HashMap<>();
353 guard.put("actor", "FOO");
354 guard.put("recipe", "bar");
355 guard.put("vfCount", "4");
356 Map<String, Object> resource = new HashMap<>();
357 resource.put("guard", guard);
358 request.setResource(resource);
360 // Ask for a decision - should get permit
362 DecisionResponse response = service.makeDecision(request);
363 LOGGER.info("Looking for Permit Decision {}", response);
364 assertThat(response).isNotNull();
365 assertThat(response.getStatus()).isNotNull();
366 assertThat(response.getStatus()).isEqualTo("Permit");
370 guard.put("vfCount", "10");
371 resource.put("guard", guard);
372 request.setResource(resource);
373 response = service.makeDecision(request);
374 LOGGER.info("Looking for Deny Decision {}", response);
375 assertThat(response).isNotNull();
376 assertThat(response.getStatus()).isNotNull();
377 assertThat(response.getStatus()).isEqualTo("Deny");
381 @SuppressWarnings("unchecked")
382 private void insertOperationEvent(DecisionRequest request) {
384 // Get the properties
386 Map<String, Object> properties = (Map<String, Object>) request.getResource().get("guard");
387 assertThat(properties).isNotNull();
391 OnapOperationsHistoryDbao newEntry = new OnapOperationsHistoryDbao();
392 newEntry.setActor(properties.get("actor").toString());
393 newEntry.setOperation(properties.get("recipe").toString());
394 newEntry.setClName(properties.get("clname").toString());
395 newEntry.setOutcome("SUCCESS");
396 newEntry.setStarttime(Date.from(Instant.now().minusMillis(20000)));
397 newEntry.setEndtime(Date.from(Instant.now()));
398 newEntry.setRequestId(UUID.randomUUID().toString());
399 newEntry.setTarget(properties.get("target").toString());
400 em.getTransaction().begin();
401 em.persist(newEntry);
402 em.getTransaction().commit();
406 public static void cleanup() throws Exception {