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.FileNotFoundException;
29 import java.io.IOException;
31 import java.time.Instant;
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 javax.persistence.EntityManager;
40 import javax.persistence.Persistence;
42 import org.junit.AfterClass;
43 import org.junit.Before;
44 import org.junit.BeforeClass;
45 import org.junit.ClassRule;
46 import org.junit.FixMethodOrder;
47 import org.junit.Test;
48 import org.junit.rules.TemporaryFolder;
49 import org.junit.runners.MethodSorters;
50 import org.onap.policy.common.utils.coder.CoderException;
51 import org.onap.policy.common.utils.coder.StandardCoder;
52 import org.onap.policy.common.utils.resources.TextFileUtils;
53 import org.onap.policy.models.decisions.concepts.DecisionRequest;
54 import org.onap.policy.models.decisions.concepts.DecisionResponse;
55 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
56 import org.onap.policy.pdp.xacml.application.common.OnapOperationsHistoryDbao;
57 import org.onap.policy.pdp.xacml.application.common.TestUtils;
58 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
59 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
60 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
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(new ToscaPolicyTypeIdentifier(
218 "onap.policies.controlloop.guard.FrequencyLimiter", "1.0.0"))).isTrue();
219 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
220 "onap.policies.controlloop.guard.FrequencyLimiter", "1.0.1"))).isFalse();
221 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
222 "onap.policies.controlloop.guard.MinMax", "1.0.0"))).isTrue();
223 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
224 "onap.policies.controlloop.guard.MinMax", "1.0.1"))).isFalse();
225 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier("onap.foo", "1.0.1"))).isFalse();
229 public void test2NoPolicies() throws CoderException {
230 LOGGER.info("**************** Running test2 ****************");
231 requestAndCheckDecision(requestVfCount1,PERMIT);
235 public void test3FrequencyLimiter() throws CoderException, FileNotFoundException, IOException,
236 XacmlApplicationException {
237 LOGGER.info("**************** Running test3 ****************");
239 // Now load the vDNS frequency limiter Policy - make sure
240 // the pdp can support it and have it load
243 TestUtils.loadPolicies("src/test/resources/vDNS.policy.guard.frequency.output.tosca.yaml", service);
245 // Zero recent actions: should get permit
247 requestAndCheckDecision(requestVfCount1,PERMIT);
249 // Add entry into operations history DB
251 insertOperationEvent(requestVfCount1);
253 // Only one recent actions: should get permit
255 requestAndCheckDecision(requestVfCount1,PERMIT);
257 // Add entry into operations history DB
259 insertOperationEvent(requestVfCount1);
261 // Two recent actions, more than specified limit of 2: should get deny
263 requestAndCheckDecision(requestVfCount1,DENY);
267 public void test4MinMax() throws CoderException, FileNotFoundException, IOException, XacmlApplicationException {
268 LOGGER.info("**************** Running test4 ****************");
270 // Now load the vDNS min max Policy - make sure
271 // the pdp can support it and have it load
274 TestUtils.loadPolicies("src/test/resources/vDNS.policy.guard.minmax.output.tosca.yaml", service);
276 // vfcount=1 below min of 2: should get a Deny
278 requestAndCheckDecision(requestVfCount1, DENY);
280 // vfcount=3 between min of 2 and max of 5: should get a Permit
282 requestAndCheckDecision(requestVfCount3, PERMIT);
284 // vfcount=6 above max of 5: should get a Deny
286 requestAndCheckDecision(requestVfCount6,DENY);
288 // Add two entry into operations history DB
290 insertOperationEvent(requestVfCount1);
291 insertOperationEvent(requestVfCount1);
293 // vfcount=3 between min of 2 and max of 5, but 2 recent actions is above frequency limit: should get a Deny
295 requestAndCheckDecision(requestVfCount3, DENY);
297 // vfcount=6 above max of 5: should get a Deny
299 requestAndCheckDecision(requestVfCount6, DENY);
303 public void test5MissingFields() throws FileNotFoundException, IOException, XacmlApplicationException,
305 LOGGER.info("**************** Running test5 ****************");
307 // Most likely we would not get a policy with missing fields passed to
308 // us from the API. But in case that happens, or we decide that some fields
309 // will be optional due to re-working of how the XACML policies are built,
310 // let's add support in for that.
312 TestUtils.loadPolicies("src/test/resources/guard.policy-minmax-missing-fields1.yaml", service);
314 // We can create a DecisionRequest on the fly - no need
315 // to have it in the .json files
317 DecisionRequest request = new DecisionRequest();
318 request.setOnapName("JUnit");
319 request.setOnapComponent("test5MissingFields");
320 request.setRequestId(UUID.randomUUID().toString());
321 request.setAction("guard");
322 Map<String, Object> guard = new HashMap<>();
323 guard.put("actor", "FOO");
324 guard.put("recipe", "bar");
325 guard.put("vfCount", "4");
326 Map<String, Object> resource = new HashMap<>();
327 resource.put("guard", guard);
328 request.setResource(resource);
330 // Ask for a decision - should get permit
332 DecisionResponse response = service.makeDecision(request);
333 LOGGER.info("Looking for Permit Decision {}", response);
334 assertThat(response).isNotNull();
335 assertThat(response.getStatus()).isNotNull();
336 assertThat(response.getStatus()).isEqualTo("Permit");
340 guard.put("vfCount", "10");
341 resource.put("guard", guard);
342 request.setResource(resource);
343 response = service.makeDecision(request);
344 LOGGER.info("Looking for Deny Decision {}", response);
345 assertThat(response).isNotNull();
346 assertThat(response.getStatus()).isNotNull();
347 assertThat(response.getStatus()).isEqualTo("Deny");
350 @SuppressWarnings("unchecked")
351 private void insertOperationEvent(DecisionRequest request) {
353 // Get the properties
355 Map<String, Object> properties = (Map<String, Object>) request.getResource().get("guard");
356 assertThat(properties).isNotNull();
360 OnapOperationsHistoryDbao newEntry = new OnapOperationsHistoryDbao();
361 newEntry.setActor(properties.get("actor").toString());
362 newEntry.setOperation(properties.get("recipe").toString());
363 newEntry.setClName(properties.get("clname").toString());
364 newEntry.setOutcome("SUCCESS");
365 newEntry.setStarttime(Date.from(Instant.now().minusMillis(20000)));
366 newEntry.setEndtime(Date.from(Instant.now()));
367 newEntry.setRequestId(UUID.randomUUID().toString());
368 newEntry.setTarget(properties.get("target").toString());
369 LOGGER.info("Inserting {}", newEntry);
370 em.getTransaction().begin();
371 em.persist(newEntry);
372 em.getTransaction().commit();
376 public static void cleanup() throws Exception {