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.TestUtils;
57 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
58 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
59 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
60 import org.onap.policy.pdp.xacml.application.common.operationshistory.CountRecentOperationsPip;
61 import org.onap.policy.pdp.xacml.application.common.operationshistory.Dbao;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
65 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
66 public class GuardPdpApplicationTest {
68 private static final Logger LOGGER = LoggerFactory.getLogger(GuardPdpApplicationTest.class);
69 private static Properties properties = new Properties();
70 private static File propertiesFile;
71 private static XacmlApplicationServiceProvider service;
72 private static DecisionRequest requestVfCount1;
73 private static DecisionRequest requestVfCount3;
74 private static DecisionRequest requestVfCount6;
75 private static StandardCoder gson = new StandardCoder();
76 private static EntityManager em;
77 private static final String DENY = "Deny";
78 private static final String PERMIT = "Permit";
81 public static final TemporaryFolder policyFolder = new TemporaryFolder();
84 * Copies the xacml.properties and policies files into
85 * temporary folder and loads the service provider saving
86 * instance of provider off for other tests to use.
89 public static void setup() throws Exception {
90 LOGGER.info("Setting up class");
92 // Setup our temporary folder
94 XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
95 propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
96 properties, myCreator);
100 ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
101 ServiceLoader.load(XacmlApplicationServiceProvider.class);
103 // Find the guard service application and save for use in all the tests
105 StringBuilder strDump = new StringBuilder("Loaded applications:" + System.lineSeparator());
106 Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
107 while (iterator.hasNext()) {
108 XacmlApplicationServiceProvider application = iterator.next();
110 // Is it our service?
112 if (application instanceof GuardPdpApplication) {
114 // Should be the first and only one
116 assertThat(service).isNull();
117 service = application;
119 strDump.append(application.applicationName());
120 strDump.append(" supports ");
121 strDump.append(application.supportedPolicyTypes());
122 strDump.append(System.lineSeparator());
124 LOGGER.info("{}", strDump);
126 // Tell it to initialize based on the properties file
127 // we just built for it.
129 service.initialize(propertiesFile.toPath().getParent());
131 // Load Decision Requests
133 requestVfCount1 = gson.decode(
134 TextFileUtils.getTextFileAsString(
135 "src/test/resources/requests/guard.vfCount.1.json"),
136 DecisionRequest.class);
137 requestVfCount3 = gson.decode(
138 TextFileUtils.getTextFileAsString(
139 "src/test/resources/requests/guard.vfCount.3.json"),
140 DecisionRequest.class);
141 requestVfCount6 = gson.decode(
142 TextFileUtils.getTextFileAsString(
143 "src/test/resources/requests/guard.vfCount.6.json"),
144 DecisionRequest.class);
146 // Create EntityManager for manipulating DB
148 String persistenceUnit = CountRecentOperationsPip.ISSUER_NAME + ".persistenceunit";
149 em = Persistence.createEntityManagerFactory(
150 GuardPdpApplicationTest.properties.getProperty(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 Dbao").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(3);
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(
228 "onap.policies.controlloop.guard.coordination.FirstBlocksSecond", "1.0.0"))).isTrue();
229 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
230 "onap.policies.controlloop.guard.coordination.FirstBlocksSecond", "1.0.1"))).isFalse();
231 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier("onap.foo", "1.0.1"))).isFalse();
235 public void test2NoPolicies() throws CoderException {
236 LOGGER.info("**************** Running test2 ****************");
237 requestAndCheckDecision(requestVfCount1,PERMIT);
241 public void test3FrequencyLimiter() throws CoderException, FileNotFoundException, IOException,
242 XacmlApplicationException {
243 LOGGER.info("**************** Running test3 ****************");
245 // Now load the vDNS frequency limiter Policy - make sure
246 // the pdp can support it and have it load
249 TestUtils.loadPolicies("src/test/resources/vDNS.policy.guard.frequency.output.tosca.yaml", service);
251 // Zero recent actions: should get permit
253 requestAndCheckDecision(requestVfCount1,PERMIT);
255 // Add entry into operations history DB
257 insertOperationEvent(requestVfCount1);
259 // Only one recent actions: should get permit
261 requestAndCheckDecision(requestVfCount1,PERMIT);
263 // Add entry into operations history DB
265 insertOperationEvent(requestVfCount1);
267 // Two recent actions, more than specified limit of 2: should get deny
269 requestAndCheckDecision(requestVfCount1,DENY);
273 public void test4MinMax() throws CoderException, FileNotFoundException, IOException, XacmlApplicationException {
274 LOGGER.info("**************** Running test4 ****************");
276 // Now load the vDNS min max Policy - make sure
277 // the pdp can support it and have it load
280 TestUtils.loadPolicies("src/test/resources/vDNS.policy.guard.minmax.output.tosca.yaml", service);
282 // vfcount=1 below min of 2: should get a Deny
284 requestAndCheckDecision(requestVfCount1, DENY);
286 // vfcount=3 between min of 2 and max of 5: should get a Permit
288 requestAndCheckDecision(requestVfCount3, PERMIT);
290 // vfcount=6 above max of 5: should get a Deny
292 requestAndCheckDecision(requestVfCount6,DENY);
294 // Add two entry into operations history DB
296 insertOperationEvent(requestVfCount1);
297 insertOperationEvent(requestVfCount1);
299 // vfcount=3 between min of 2 and max of 5, but 2 recent actions is above frequency limit: should get a Deny
301 requestAndCheckDecision(requestVfCount3, DENY);
303 // vfcount=6 above max of 5: should get a Deny
305 requestAndCheckDecision(requestVfCount6, DENY);
309 public void test5MissingFields() throws FileNotFoundException, IOException, XacmlApplicationException,
311 LOGGER.info("**************** Running test5 ****************");
313 // Most likely we would not get a policy with missing fields passed to
314 // us from the API. But in case that happens, or we decide that some fields
315 // will be optional due to re-working of how the XACML policies are built,
316 // let's add support in for that.
318 TestUtils.loadPolicies("src/test/resources/guard.policy-minmax-missing-fields1.yaml", service);
320 // We can create a DecisionRequest on the fly - no need
321 // to have it in the .json files
323 DecisionRequest request = new DecisionRequest();
324 request.setOnapName("JUnit");
325 request.setOnapComponent("test5MissingFields");
326 request.setRequestId(UUID.randomUUID().toString());
327 request.setAction("guard");
328 Map<String, Object> guard = new HashMap<>();
329 guard.put("actor", "FOO");
330 guard.put("recipe", "bar");
331 guard.put("vfCount", "4");
332 Map<String, Object> resource = new HashMap<>();
333 resource.put("guard", guard);
334 request.setResource(resource);
336 // Ask for a decision - should get permit
338 DecisionResponse response = service.makeDecision(request);
339 LOGGER.info("Looking for Permit Decision {}", response);
340 assertThat(response).isNotNull();
341 assertThat(response.getStatus()).isNotNull();
342 assertThat(response.getStatus()).isEqualTo("Permit");
346 guard.put("vfCount", "10");
347 resource.put("guard", guard);
348 request.setResource(resource);
349 response = service.makeDecision(request);
350 LOGGER.info("Looking for Deny Decision {}", response);
351 assertThat(response).isNotNull();
352 assertThat(response.getStatus()).isNotNull();
353 assertThat(response.getStatus()).isEqualTo("Deny");
356 @SuppressWarnings("unchecked")
357 private void insertOperationEvent(DecisionRequest request) {
359 // Get the properties
361 Map<String, Object> properties = (Map<String, Object>) request.getResource().get("guard");
362 assertThat(properties).isNotNull();
366 Dbao newEntry = new Dbao();
367 newEntry.setActor(properties.get("actor").toString());
368 newEntry.setOperation(properties.get("recipe").toString());
369 newEntry.setClosedLoopName(properties.get("clname").toString());
370 newEntry.setOutcome("SUCCESS");
371 newEntry.setStarttime(Date.from(Instant.now().minusMillis(20000)));
372 newEntry.setEndtime(Date.from(Instant.now()));
373 newEntry.setRequestId(UUID.randomUUID().toString());
374 newEntry.setTarget(properties.get("target").toString());
375 LOGGER.info("Inserting {}", newEntry);
376 em.getTransaction().begin();
377 em.persist(newEntry);
378 em.getTransaction().commit();
382 * Close the entity manager.
385 public static void cleanup() throws Exception {