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;
27 import com.att.research.xacml.api.Response;
30 import java.io.FileNotFoundException;
31 import java.io.IOException;
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.apache.commons.lang3.tuple.Pair;
45 import org.junit.AfterClass;
46 import org.junit.Before;
47 import org.junit.BeforeClass;
48 import org.junit.ClassRule;
49 import org.junit.FixMethodOrder;
50 import org.junit.Test;
51 import org.junit.rules.TemporaryFolder;
52 import org.junit.runners.MethodSorters;
53 import org.onap.policy.common.utils.coder.CoderException;
54 import org.onap.policy.common.utils.coder.StandardCoder;
55 import org.onap.policy.common.utils.resources.TextFileUtils;
56 import org.onap.policy.models.decisions.concepts.DecisionRequest;
57 import org.onap.policy.models.decisions.concepts.DecisionResponse;
58 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
59 import org.onap.policy.pdp.xacml.application.common.TestUtils;
60 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
61 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
62 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
63 import org.onap.policy.pdp.xacml.application.common.operationshistory.CountRecentOperationsPip;
64 import org.onap.policy.pdp.xacml.application.common.operationshistory.Dbao;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
68 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
69 public class GuardPdpApplicationTest {
71 private static final Logger LOGGER = LoggerFactory.getLogger(GuardPdpApplicationTest.class);
72 private static Properties properties = new Properties();
73 private static File propertiesFile;
74 private static XacmlApplicationServiceProvider service;
75 private static DecisionRequest requestVfCount1;
76 private static DecisionRequest requestVfCount3;
77 private static DecisionRequest requestVfCount6;
78 private static StandardCoder gson = new StandardCoder();
79 private static EntityManager em;
80 private static final String DENY = "Deny";
81 private static final String PERMIT = "Permit";
84 public static final TemporaryFolder policyFolder = new TemporaryFolder();
87 * Copies the xacml.properties and policies files into
88 * temporary folder and loads the service provider saving
89 * instance of provider off for other tests to use.
92 public static void setup() throws Exception {
93 LOGGER.info("Setting up class");
95 // Setup our temporary folder
97 XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
98 propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
99 properties, myCreator);
103 ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
104 ServiceLoader.load(XacmlApplicationServiceProvider.class);
106 // Find the guard service application and save for use in all the tests
108 StringBuilder strDump = new StringBuilder("Loaded applications:" + System.lineSeparator());
109 Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
110 while (iterator.hasNext()) {
111 XacmlApplicationServiceProvider application = iterator.next();
113 // Is it our service?
115 if (application instanceof GuardPdpApplication) {
117 // Should be the first and only one
119 assertThat(service).isNull();
120 service = application;
122 strDump.append(application.applicationName());
123 strDump.append(" supports ");
124 strDump.append(application.supportedPolicyTypes());
125 strDump.append(System.lineSeparator());
127 LOGGER.info("{}", strDump);
129 // Tell it to initialize based on the properties file
130 // we just built for it.
132 service.initialize(propertiesFile.toPath().getParent());
134 // Load Decision Requests
136 requestVfCount1 = gson.decode(
137 TextFileUtils.getTextFileAsString(
138 "src/test/resources/requests/guard.vfCount.1.json"),
139 DecisionRequest.class);
140 requestVfCount3 = gson.decode(
141 TextFileUtils.getTextFileAsString(
142 "src/test/resources/requests/guard.vfCount.3.json"),
143 DecisionRequest.class);
144 requestVfCount6 = gson.decode(
145 TextFileUtils.getTextFileAsString(
146 "src/test/resources/requests/guard.vfCount.6.json"),
147 DecisionRequest.class);
149 // Create EntityManager for manipulating DB
151 String persistenceUnit = CountRecentOperationsPip.ISSUER_NAME + ".persistenceunit";
152 em = Persistence.createEntityManagerFactory(
153 GuardPdpApplicationTest.properties.getProperty(persistenceUnit), properties)
154 .createEntityManager();
158 * Clears the database before each test.
162 public void startClean() throws Exception {
163 em.getTransaction().begin();
164 em.createQuery("DELETE FROM Dbao").executeUpdate();
165 em.getTransaction().commit();
169 * Check that decision matches expectation.
171 * @param expected from the response
172 * @param response received
175 public void checkDecision(String expected, DecisionResponse response) throws CoderException {
176 LOGGER.info("Looking for {} Decision", expected);
177 assertThat(response).isNotNull();
178 assertThat(response.getStatus()).isNotNull();
179 assertThat(response.getStatus()).isEqualTo(expected);
181 // Dump it out as Json
183 LOGGER.info(gson.encode(response));
187 * Request a decision and check that it matches expectation.
189 * @param request to send to Xacml PDP
190 * @param expected from the response
193 public void requestAndCheckDecision(DecisionRequest request, String expected) throws CoderException {
195 // Ask for a decision
197 Pair<DecisionResponse, Response> decision = service.makeDecision(request);
201 checkDecision(expected, decision.getKey());
205 public void test1Basics() throws CoderException, IOException {
206 LOGGER.info("**************** Running test1 ****************");
208 // Make sure there's an application name
210 assertThat(service.applicationName()).isNotEmpty();
214 assertThat(service.actionDecisionsSupported().size()).isEqualTo(1);
215 assertThat(service.actionDecisionsSupported()).contains("guard");
217 // Ensure it has the supported policy types and
218 // can support the correct policy types.
220 assertThat(service.supportedPolicyTypes()).isNotEmpty();
221 assertThat(service.supportedPolicyTypes().size()).isEqualTo(4);
222 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
223 "onap.policies.controlloop.guard.FrequencyLimiter", "1.0.0"))).isTrue();
224 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
225 "onap.policies.controlloop.guard.FrequencyLimiter", "1.0.1"))).isFalse();
226 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
227 "onap.policies.controlloop.guard.MinMax", "1.0.0"))).isTrue();
228 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
229 "onap.policies.controlloop.guard.MinMax", "1.0.1"))).isFalse();
230 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
231 "onap.policies.controlloop.guard.Blacklist", "1.0.0"))).isTrue();
232 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
233 "onap.policies.controlloop.guard.Blacklist", "1.0.1"))).isFalse();
234 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
235 "onap.policies.controlloop.guard.coordination.FirstBlocksSecond", "1.0.0"))).isTrue();
236 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
237 "onap.policies.controlloop.guard.coordination.FirstBlocksSecond", "1.0.1"))).isFalse();
238 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier("onap.foo", "1.0.1"))).isFalse();
242 public void test2NoPolicies() throws CoderException {
243 LOGGER.info("**************** Running test2 ****************");
244 requestAndCheckDecision(requestVfCount1,PERMIT);
248 public void test3FrequencyLimiter() throws CoderException, FileNotFoundException, IOException,
249 XacmlApplicationException {
250 LOGGER.info("**************** Running test3 ****************");
252 // Now load the vDNS frequency limiter Policy - make sure
253 // the pdp can support it and have it load
256 TestUtils.loadPolicies("src/test/resources/vDNS.policy.guard.frequency.output.tosca.yaml", service);
258 // Zero recent actions: should get permit
260 requestAndCheckDecision(requestVfCount1,PERMIT);
262 // Add entry into operations history DB
264 insertOperationEvent(requestVfCount1);
266 // Only one recent actions: should get permit
268 requestAndCheckDecision(requestVfCount1,PERMIT);
270 // Add entry into operations history DB
272 insertOperationEvent(requestVfCount1);
274 // Two recent actions, more than specified limit of 2: should get deny
276 requestAndCheckDecision(requestVfCount1,DENY);
280 public void test4MinMax() throws CoderException, FileNotFoundException, IOException, XacmlApplicationException {
281 LOGGER.info("**************** Running test4 ****************");
283 // Now load the vDNS min max Policy - make sure
284 // the pdp can support it and have it load
287 TestUtils.loadPolicies("src/test/resources/vDNS.policy.guard.minmax.output.tosca.yaml", service);
289 // vfcount=1 below min of 2: should get a Deny
291 requestAndCheckDecision(requestVfCount1, DENY);
293 // vfcount=3 between min of 2 and max of 5: should get a Permit
295 requestAndCheckDecision(requestVfCount3, PERMIT);
297 // vfcount=6 above max of 5: should get a Deny
299 requestAndCheckDecision(requestVfCount6,DENY);
301 // Add two entry into operations history DB
303 insertOperationEvent(requestVfCount1);
304 insertOperationEvent(requestVfCount1);
306 // vfcount=3 between min of 2 and max of 5, but 2 recent actions is above frequency limit: should get a Deny
308 requestAndCheckDecision(requestVfCount3, DENY);
310 // vfcount=6 above max of 5: should get a Deny
312 requestAndCheckDecision(requestVfCount6, DENY);
316 public void test5MissingFields() throws FileNotFoundException, IOException, XacmlApplicationException,
318 LOGGER.info("**************** Running test5 ****************");
320 // Most likely we would not get a policy with missing fields passed to
321 // us from the API. But in case that happens, or we decide that some fields
322 // will be optional due to re-working of how the XACML policies are built,
323 // let's add support in for that.
325 TestUtils.loadPolicies("src/test/resources/guard.policy-minmax-missing-fields1.yaml", service);
327 // We can create a DecisionRequest on the fly - no need
328 // to have it in the .json files
330 DecisionRequest request = new DecisionRequest();
331 request.setOnapName("JUnit");
332 request.setOnapComponent("test5MissingFields");
333 request.setRequestId(UUID.randomUUID().toString());
334 request.setAction("guard");
335 Map<String, Object> guard = new HashMap<>();
336 guard.put("actor", "FOO");
337 guard.put("recipe", "bar");
338 guard.put("vfCount", "4");
339 Map<String, Object> resource = new HashMap<>();
340 resource.put("guard", guard);
341 request.setResource(resource);
343 // Ask for a decision - should get permit
345 Pair<DecisionResponse, Response> decision = service.makeDecision(request);
346 LOGGER.info("Looking for Permit Decision {}", decision.getKey());
347 assertThat(decision.getKey()).isNotNull();
348 assertThat(decision.getKey().getStatus()).isNotNull();
349 assertThat(decision.getKey().getStatus()).isEqualTo("Permit");
353 guard.put("vfCount", "10");
354 resource.put("guard", guard);
355 request.setResource(resource);
356 decision = service.makeDecision(request);
357 LOGGER.info("Looking for Deny Decision {}", decision.getKey());
358 assertThat(decision.getKey()).isNotNull();
359 assertThat(decision.getKey().getStatus()).isNotNull();
360 assertThat(decision.getKey().getStatus()).isEqualTo("Deny");
364 public void test6Blacklist() throws CoderException, XacmlApplicationException {
365 LOGGER.info("**************** Running test4 ****************");
367 // Setup requestVfCount1 to point to another target for this test
369 ((Map<String, Object>)requestVfCount3.getResource().get("guard")).put("targets", "vLoadBalancer-01");
371 // vfcount=1 above min of 2: should get a permit
373 requestAndCheckDecision(requestVfCount3, PERMIT);
375 // Now load the vDNS blacklist policy
377 TestUtils.loadPolicies("src/test/resources/vDNS.policy.guard.blacklist.output.tosca.yaml", service);
379 // vfcount=1 above min of 2: should get a permit
381 requestAndCheckDecision(requestVfCount3, DENY);
384 @SuppressWarnings("unchecked")
385 private void insertOperationEvent(DecisionRequest request) {
387 // Get the properties
389 Map<String, Object> properties = (Map<String, Object>) request.getResource().get("guard");
390 assertThat(properties).isNotNull();
394 Dbao newEntry = new Dbao();
395 newEntry.setActor(properties.get("actor").toString());
396 newEntry.setOperation(properties.get("recipe").toString());
397 newEntry.setClosedLoopName(properties.get("clname").toString());
398 newEntry.setOutcome("SUCCESS");
399 newEntry.setStarttime(Date.from(Instant.now().minusMillis(20000)));
400 newEntry.setEndtime(Date.from(Instant.now()));
401 newEntry.setRequestId(UUID.randomUUID().toString());
402 newEntry.setTarget(properties.get("target").toString());
403 LOGGER.info("Inserting {}", newEntry);
404 em.getTransaction().begin();
405 em.persist(newEntry);
406 em.getTransaction().commit();
410 * Close the entity manager.
413 public static void cleanup() throws Exception {