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.endpoints.parameters.RestServerParameters;
54 import org.onap.policy.common.utils.coder.CoderException;
55 import org.onap.policy.common.utils.coder.StandardCoder;
56 import org.onap.policy.common.utils.resources.TextFileUtils;
57 import org.onap.policy.models.decisions.concepts.DecisionRequest;
58 import org.onap.policy.models.decisions.concepts.DecisionResponse;
59 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
60 import org.onap.policy.pdp.xacml.application.common.TestUtils;
61 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
62 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
63 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
64 import org.onap.policy.pdp.xacml.application.common.operationshistory.CountRecentOperationsPip;
65 import org.onap.policy.pdp.xacml.application.common.operationshistory.Dbao;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
69 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
70 public class GuardPdpApplicationTest {
72 private static final Logger LOGGER = LoggerFactory.getLogger(GuardPdpApplicationTest.class);
73 private static Properties properties = new Properties();
74 private static File propertiesFile;
75 private static RestServerParameters clientParams = new RestServerParameters();
76 private static XacmlApplicationServiceProvider service;
77 private static DecisionRequest requestVfCount1;
78 private static DecisionRequest requestVfCount3;
79 private static DecisionRequest requestVfCount6;
80 private static StandardCoder gson = new StandardCoder();
81 private static EntityManager em;
82 private static final String DENY = "Deny";
83 private static final String PERMIT = "Permit";
86 public static final TemporaryFolder policyFolder = new TemporaryFolder();
89 * Copies the xacml.properties and policies files into
90 * temporary folder and loads the service provider saving
91 * instance of provider off for other tests to use.
94 public static void setup() throws Exception {
95 LOGGER.info("Setting up class");
97 // Setup our temporary folder
99 XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
100 propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
101 properties, myCreator);
105 ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
106 ServiceLoader.load(XacmlApplicationServiceProvider.class);
108 // Find the guard service application and save for use in all the tests
110 StringBuilder strDump = new StringBuilder("Loaded applications:" + System.lineSeparator());
111 Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
112 while (iterator.hasNext()) {
113 XacmlApplicationServiceProvider application = iterator.next();
115 // Is it our service?
117 if (application instanceof GuardPdpApplication) {
119 // Should be the first and only one
121 assertThat(service).isNull();
122 service = application;
124 strDump.append(application.applicationName());
125 strDump.append(" supports ");
126 strDump.append(application.supportedPolicyTypes());
127 strDump.append(System.lineSeparator());
129 LOGGER.info("{}", strDump);
131 // Tell it to initialize based on the properties file
132 // we just built for it.
134 service.initialize(propertiesFile.toPath().getParent(), clientParams);
136 // Load Decision Requests
138 requestVfCount1 = gson.decode(
139 TextFileUtils.getTextFileAsString(
140 "src/test/resources/requests/guard.vfCount.1.json"),
141 DecisionRequest.class);
142 requestVfCount3 = gson.decode(
143 TextFileUtils.getTextFileAsString(
144 "src/test/resources/requests/guard.vfCount.3.json"),
145 DecisionRequest.class);
146 requestVfCount6 = gson.decode(
147 TextFileUtils.getTextFileAsString(
148 "src/test/resources/requests/guard.vfCount.6.json"),
149 DecisionRequest.class);
151 // Create EntityManager for manipulating DB
153 String persistenceUnit = CountRecentOperationsPip.ISSUER_NAME + ".persistenceunit";
154 em = Persistence.createEntityManagerFactory(
155 GuardPdpApplicationTest.properties.getProperty(persistenceUnit), properties)
156 .createEntityManager();
160 * Clears the database before each test.
164 public void startClean() throws Exception {
165 em.getTransaction().begin();
166 em.createQuery("DELETE FROM Dbao").executeUpdate();
167 em.getTransaction().commit();
171 * Check that decision matches expectation.
173 * @param expected from the response
174 * @param response received
177 public void checkDecision(String expected, DecisionResponse response) throws CoderException {
178 LOGGER.info("Looking for {} Decision", expected);
179 assertThat(response).isNotNull();
180 assertThat(response.getStatus()).isNotNull();
181 assertThat(response.getStatus()).isEqualTo(expected);
183 // Dump it out as Json
185 LOGGER.info(gson.encode(response));
189 * Request a decision and check that it matches expectation.
191 * @param request to send to Xacml PDP
192 * @param expected from the response
195 public void requestAndCheckDecision(DecisionRequest request, String expected) throws CoderException {
197 // Ask for a decision
199 Pair<DecisionResponse, Response> decision = service.makeDecision(request);
203 checkDecision(expected, decision.getKey());
207 public void test1Basics() throws CoderException, IOException {
208 LOGGER.info("**************** Running test1 ****************");
210 // Make sure there's an application name
212 assertThat(service.applicationName()).isNotEmpty();
216 assertThat(service.actionDecisionsSupported().size()).isEqualTo(1);
217 assertThat(service.actionDecisionsSupported()).contains("guard");
219 // Ensure it has the supported policy types and
220 // can support the correct policy types.
222 assertThat(service.supportedPolicyTypes()).isNotEmpty();
223 assertThat(service.supportedPolicyTypes().size()).isEqualTo(4);
224 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
225 "onap.policies.controlloop.guard.FrequencyLimiter", "1.0.0"))).isTrue();
226 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
227 "onap.policies.controlloop.guard.FrequencyLimiter", "1.0.1"))).isFalse();
228 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
229 "onap.policies.controlloop.guard.MinMax", "1.0.0"))).isTrue();
230 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
231 "onap.policies.controlloop.guard.MinMax", "1.0.1"))).isFalse();
232 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
233 "onap.policies.controlloop.guard.Blacklist", "1.0.0"))).isTrue();
234 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
235 "onap.policies.controlloop.guard.Blacklist", "1.0.1"))).isFalse();
236 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
237 "onap.policies.controlloop.guard.coordination.FirstBlocksSecond", "1.0.0"))).isTrue();
238 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
239 "onap.policies.controlloop.guard.coordination.FirstBlocksSecond", "1.0.1"))).isFalse();
240 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier("onap.foo", "1.0.1"))).isFalse();
244 public void test2NoPolicies() throws CoderException {
245 LOGGER.info("**************** Running test2 ****************");
246 requestAndCheckDecision(requestVfCount1,PERMIT);
250 public void test3FrequencyLimiter() throws CoderException, FileNotFoundException, IOException,
251 XacmlApplicationException {
252 LOGGER.info("**************** Running test3 ****************");
254 // Now load the vDNS frequency limiter Policy - make sure
255 // the pdp can support it and have it load
258 TestUtils.loadPolicies("src/test/resources/vDNS.policy.guard.frequency.output.tosca.yaml", service);
260 // Zero recent actions: should get permit
262 requestAndCheckDecision(requestVfCount1,PERMIT);
264 // Add entry into operations history DB
266 insertOperationEvent(requestVfCount1);
268 // Only one recent actions: should get permit
270 requestAndCheckDecision(requestVfCount1,PERMIT);
272 // Add entry into operations history DB
274 insertOperationEvent(requestVfCount1);
276 // Two recent actions, more than specified limit of 2: should get deny
278 requestAndCheckDecision(requestVfCount1,DENY);
282 public void test4MinMax() throws CoderException, FileNotFoundException, IOException, XacmlApplicationException {
283 LOGGER.info("**************** Running test4 ****************");
285 // Now load the vDNS min max Policy - make sure
286 // the pdp can support it and have it load
289 TestUtils.loadPolicies("src/test/resources/vDNS.policy.guard.minmax.output.tosca.yaml", service);
291 // vfcount=1 below min of 2: should get a Deny
293 requestAndCheckDecision(requestVfCount1, DENY);
295 // vfcount=3 between min of 2 and max of 5: should get a Permit
297 requestAndCheckDecision(requestVfCount3, PERMIT);
299 // vfcount=6 above max of 5: should get a Deny
301 requestAndCheckDecision(requestVfCount6,DENY);
303 // Add two entry into operations history DB
305 insertOperationEvent(requestVfCount1);
306 insertOperationEvent(requestVfCount1);
308 // vfcount=3 between min of 2 and max of 5, but 2 recent actions is above frequency limit: should get a Deny
310 requestAndCheckDecision(requestVfCount3, DENY);
312 // vfcount=6 above max of 5: should get a Deny
314 requestAndCheckDecision(requestVfCount6, DENY);
318 public void test5MissingFields() throws FileNotFoundException, IOException, XacmlApplicationException,
320 LOGGER.info("**************** Running test5 ****************");
322 // Most likely we would not get a policy with missing fields passed to
323 // us from the API. But in case that happens, or we decide that some fields
324 // will be optional due to re-working of how the XACML policies are built,
325 // let's add support in for that.
327 TestUtils.loadPolicies("src/test/resources/guard.policy-minmax-missing-fields1.yaml", service);
329 // We can create a DecisionRequest on the fly - no need
330 // to have it in the .json files
332 DecisionRequest request = new DecisionRequest();
333 request.setOnapName("JUnit");
334 request.setOnapComponent("test5MissingFields");
335 request.setRequestId(UUID.randomUUID().toString());
336 request.setAction("guard");
337 Map<String, Object> guard = new HashMap<>();
338 guard.put("actor", "FOO");
339 guard.put("recipe", "bar");
340 guard.put("vfCount", "4");
341 Map<String, Object> resource = new HashMap<>();
342 resource.put("guard", guard);
343 request.setResource(resource);
345 // Ask for a decision - should get permit
347 Pair<DecisionResponse, Response> decision = service.makeDecision(request);
348 LOGGER.info("Looking for Permit Decision {}", decision.getKey());
349 assertThat(decision.getKey()).isNotNull();
350 assertThat(decision.getKey().getStatus()).isNotNull();
351 assertThat(decision.getKey().getStatus()).isEqualTo("Permit");
355 guard.put("vfCount", "10");
356 resource.put("guard", guard);
357 request.setResource(resource);
358 decision = service.makeDecision(request);
359 LOGGER.info("Looking for Deny Decision {}", decision.getKey());
360 assertThat(decision.getKey()).isNotNull();
361 assertThat(decision.getKey().getStatus()).isNotNull();
362 assertThat(decision.getKey().getStatus()).isEqualTo("Deny");
365 @SuppressWarnings("unchecked")
367 public void test6Blacklist() throws CoderException, XacmlApplicationException {
368 LOGGER.info("**************** Running test4 ****************");
370 // Setup requestVfCount1 to point to another target for this test
372 ((Map<String, Object>)requestVfCount3.getResource().get("guard")).put("targets", "vLoadBalancer-01");
374 // vfcount=1 above min of 2: should get a permit
376 requestAndCheckDecision(requestVfCount3, PERMIT);
378 // Now load the vDNS blacklist policy
380 TestUtils.loadPolicies("src/test/resources/vDNS.policy.guard.blacklist.output.tosca.yaml", service);
382 // vfcount=1 above min of 2: should get a permit
384 requestAndCheckDecision(requestVfCount3, DENY);
387 @SuppressWarnings("unchecked")
388 private void insertOperationEvent(DecisionRequest request) {
390 // Get the properties
392 Map<String, Object> properties = (Map<String, Object>) request.getResource().get("guard");
393 assertThat(properties).isNotNull();
397 Dbao newEntry = new Dbao();
398 newEntry.setActor(properties.get("actor").toString());
399 newEntry.setOperation(properties.get("recipe").toString());
400 newEntry.setClosedLoopName(properties.get("clname").toString());
401 newEntry.setOutcome("SUCCESS");
402 newEntry.setStarttime(Date.from(Instant.now().minusMillis(20000)));
403 newEntry.setEndtime(Date.from(Instant.now()));
404 newEntry.setRequestId(UUID.randomUUID().toString());
405 newEntry.setTarget(properties.get("target").toString());
406 LOGGER.info("Inserting {}", newEntry);
407 em.getTransaction().begin();
408 em.persist(newEntry);
409 em.getTransaction().commit();
413 * Close the entity manager.
416 public static void cleanup() throws Exception {