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.pdp.xacml.application.common.OnapOperationsHistoryDbao;
58 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
59 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62 import org.yaml.snakeyaml.Yaml;
64 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
65 public class GuardPdpApplicationTest {
67 private static final Logger LOGGER = LoggerFactory.getLogger(GuardPdpApplicationTest.class);
68 private static Properties properties = new Properties();
69 private static File propertiesFile;
70 private static XacmlApplicationServiceProvider service;
71 private static DecisionRequest requestVfCount1;
72 private static DecisionRequest requestVfCount3;
73 private static DecisionRequest requestVfCount6;
74 private static StandardCoder gson = new StandardCoder();
75 private static EntityManager em;
76 private static final String DENY = "Deny";
77 private static final String PERMIT = "Permit";
80 public static final TemporaryFolder policyFolder = new TemporaryFolder();
83 * Copies the xacml.properties and policies files into
84 * temporary folder and loads the service provider saving
85 * instance of provider off for other tests to use.
88 public static void setUp() throws Exception {
89 LOGGER.info("Setting up class");
91 // Setup our temporary folder
93 XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
94 propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
95 properties, myCreator);
99 ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
100 ServiceLoader.load(XacmlApplicationServiceProvider.class);
102 // Find the guard service application and save for use in all the tests
104 StringBuilder strDump = new StringBuilder("Loaded applications:" + System.lineSeparator());
105 Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
106 while (iterator.hasNext()) {
107 XacmlApplicationServiceProvider application = iterator.next();
109 // Is it our service?
111 if (application instanceof GuardPdpApplication) {
113 // Should be the first and only one
115 assertThat(service).isNull();
116 service = application;
118 strDump.append(application.applicationName());
119 strDump.append(" supports ");
120 strDump.append(application.supportedPolicyTypes());
121 strDump.append(System.lineSeparator());
123 LOGGER.info("{}", strDump);
125 // Tell it to initialize based on the properties file
126 // we just built for it.
128 service.initialize(propertiesFile.toPath().getParent());
130 // Load Decision Requests
132 requestVfCount1 = gson.decode(
133 TextFileUtils.getTextFileAsString(
134 "../../main/src/test/resources/decisions/decision.guard.vfCount.1.input.json"),
135 DecisionRequest.class);
136 requestVfCount3 = gson.decode(
137 TextFileUtils.getTextFileAsString(
138 "../../main/src/test/resources/decisions/decision.guard.vfCount.3.input.json"),
139 DecisionRequest.class);
140 requestVfCount6 = gson.decode(
141 TextFileUtils.getTextFileAsString(
142 "../../main/src/test/resources/decisions/decision.guard.vfCount.6.input.json"),
143 DecisionRequest.class);
145 // Create EntityManager for manipulating DB
147 em = Persistence.createEntityManagerFactory(
148 GuardPdpApplicationTest.properties.getProperty("historydb.persistenceunit"), properties)
149 .createEntityManager();
153 * Clears the database before each test.
157 public void startClean() throws Exception {
158 em.getTransaction().begin();
159 em.createQuery("DELETE FROM OnapOperationsHistoryDbao").executeUpdate();
160 em.getTransaction().commit();
164 * Check that decision matches expectation.
166 * @param expected from the response
167 * @param response received
170 public void checkDecision(String expected, DecisionResponse response) throws CoderException {
171 LOGGER.info("Looking for {} Decision", expected);
172 assertThat(response).isNotNull();
173 assertThat(response.getStatus()).isNotNull();
174 assertThat(response.getStatus()).isEqualTo(expected);
176 // Dump it out as Json
178 LOGGER.info(gson.encode(response));
182 * Request a decision and check that it matches expectation.
184 * @param request to send to Xacml PDP
185 * @param expected from the response
188 public void requestAndCheckDecision(DecisionRequest request, String expected) throws CoderException {
190 // Ask for a decision
192 DecisionResponse response = service.makeDecision(request);
196 checkDecision(expected, response);
200 public void test1Basics() throws CoderException, IOException {
201 LOGGER.info("**************** Running test1 ****************");
203 // Make sure there's an application name
205 assertThat(service.applicationName()).isNotEmpty();
209 assertThat(service.actionDecisionsSupported().size()).isEqualTo(1);
210 assertThat(service.actionDecisionsSupported()).contains("guard");
212 // Ensure it has the supported policy types and
213 // can support the correct policy types.
215 assertThat(service.supportedPolicyTypes()).isNotEmpty();
216 assertThat(service.supportedPolicyTypes().size()).isEqualTo(2);
217 assertThat(service.canSupportPolicyType("onap.policies.controlloop.guard.FrequencyLimiter", "1.0.0"))
219 assertThat(service.canSupportPolicyType("onap.policies.controlloop.guard.FrequencyLimiter", "1.0.1"))
221 assertThat(service.canSupportPolicyType("onap.policies.controlloop.guard.MinMax", "1.0.0")).isTrue();
222 assertThat(service.canSupportPolicyType("onap.policies.controlloop.guard.MinMax", "1.0.1")).isFalse();
223 assertThat(service.canSupportPolicyType("onap.foo", "1.0.1")).isFalse();
227 public void test2NoPolicies() throws CoderException {
228 LOGGER.info("**************** Running test2 ****************");
229 requestAndCheckDecision(requestVfCount1,PERMIT);
233 public void test3FrequencyLimiter() throws CoderException, FileNotFoundException, IOException {
234 LOGGER.info("**************** Running test3 ****************");
236 // Now load the vDNS frequency limiter Policy - make sure
237 // the pdp can support it and have it load
240 try (InputStream is = new FileInputStream("src/test/resources/vDNS.policy.guard.frequency.output.tosca.yaml")) {
242 // Have yaml parse it
244 Yaml yaml = new Yaml();
245 Map<String, Object> toscaObject = yaml.load(is);
249 service.loadPolicies(toscaObject);
252 // Zero recent actions: should get permit
254 requestAndCheckDecision(requestVfCount1,PERMIT);
256 // Add entry into operations history DB
258 insertOperationEvent(requestVfCount1);
260 // Only one recent actions: should get permit
262 requestAndCheckDecision(requestVfCount1,PERMIT);
264 // Add entry into operations history DB
266 insertOperationEvent(requestVfCount1);
268 // Two recent actions, more than specified limit of 2: should get deny
270 requestAndCheckDecision(requestVfCount1,DENY);
274 public void test4MinMax() throws CoderException, FileNotFoundException, IOException {
275 LOGGER.info("**************** Running test4 ****************");
277 // Now load the vDNS min max Policy - make sure
278 // the pdp can support it and have it load
281 try (InputStream is = new FileInputStream("src/test/resources/vDNS.policy.guard.minmax.output.tosca.yaml")) {
283 // Have yaml parse it
285 Yaml yaml = new Yaml();
286 Map<String, Object> toscaObject = yaml.load(is);
290 service.loadPolicies(toscaObject);
293 // vfcount=1 below min of 2: should get a Deny
295 requestAndCheckDecision(requestVfCount1, DENY);
297 // vfcount=3 between min of 2 and max of 5: should get a Permit
299 requestAndCheckDecision(requestVfCount3, PERMIT);
301 // vfcount=6 above max of 5: should get a Deny
303 requestAndCheckDecision(requestVfCount6,DENY);
305 // Add two entry into operations history DB
307 insertOperationEvent(requestVfCount1);
308 insertOperationEvent(requestVfCount1);
310 // vfcount=3 between min of 2 and max of 5, but 2 recent actions is above frequency limit: should get a Deny
312 requestAndCheckDecision(requestVfCount3, DENY);
314 // vfcount=6 above max of 5: should get a Deny
316 requestAndCheckDecision(requestVfCount6, DENY);
320 public void test5MissingFields() throws FileNotFoundException, IOException {
321 LOGGER.info("**************** Running test5 ****************");
323 // Most likely we would not get a policy with missing fields passed to
324 // us from the API. But in case that happens, or we decide that some fields
325 // will be optional due to re-working of how the XACML policies are built,
326 // let's add support in for that.
328 try (InputStream is = new FileInputStream("src/test/resources/guard.policy-minmax-missing-fields1.yaml")) {
330 // Have yaml parse it
332 Yaml yaml = new Yaml();
333 Map<String, Object> toscaObject = yaml.load(is);
337 service.loadPolicies(toscaObject);
339 // We can create a DecisionRequest on the fly - no need
340 // to have it in the .json files
342 DecisionRequest request = new DecisionRequest();
343 request.setOnapName("JUnit");
344 request.setOnapComponent("test5MissingFields");
345 request.setRequestId(UUID.randomUUID().toString());
346 request.setAction("guard");
347 Map<String, Object> guard = new HashMap<>();
348 guard.put("actor", "FOO");
349 guard.put("recipe", "bar");
350 guard.put("vfCount", "4");
351 Map<String, Object> resource = new HashMap<>();
352 resource.put("guard", guard);
353 request.setResource(resource);
355 // Ask for a decision - should get permit
357 DecisionResponse response = service.makeDecision(request);
358 LOGGER.info("Looking for Permit Decision {}", response);
359 assertThat(response).isNotNull();
360 assertThat(response.getStatus()).isNotNull();
361 assertThat(response.getStatus()).isEqualTo("Permit");
365 guard.put("vfCount", "10");
366 resource.put("guard", guard);
367 request.setResource(resource);
368 response = service.makeDecision(request);
369 LOGGER.info("Looking for Deny Decision {}", response);
370 assertThat(response).isNotNull();
371 assertThat(response.getStatus()).isNotNull();
372 assertThat(response.getStatus()).isEqualTo("Deny");
376 @SuppressWarnings("unchecked")
377 private void insertOperationEvent(DecisionRequest request) {
379 // Get the properties
381 Map<String, Object> properties = (Map<String, Object>) request.getResource().get("guard");
382 assertThat(properties).isNotNull();
386 OnapOperationsHistoryDbao newEntry = new OnapOperationsHistoryDbao();
387 newEntry.setActor(properties.get("actor").toString());
388 newEntry.setOperation(properties.get("recipe").toString());
389 newEntry.setClName(properties.get("clname").toString());
390 newEntry.setOutcome("SUCCESS");
391 newEntry.setStarttime(Date.from(Instant.now().minusMillis(20000)));
392 newEntry.setEndtime(Date.from(Instant.now()));
393 newEntry.setRequestId(UUID.randomUUID().toString());
394 newEntry.setTarget(properties.get("target").toString());
395 em.getTransaction().begin();
396 em.persist(newEntry);
397 em.getTransaction().commit();
401 public static void cleanup() throws Exception {