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;
29 import java.io.FileNotFoundException;
30 import java.io.IOException;
32 import java.time.Instant;
33 import java.util.HashMap;
34 import java.util.Iterator;
36 import java.util.Properties;
37 import java.util.ServiceLoader;
38 import java.util.UUID;
39 import javax.persistence.EntityManager;
40 import javax.persistence.Persistence;
41 import org.apache.commons.lang3.tuple.Pair;
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.endpoints.parameters.RestServerParameters;
51 import org.onap.policy.common.utils.coder.CoderException;
52 import org.onap.policy.common.utils.coder.StandardCoder;
53 import org.onap.policy.common.utils.resources.TextFileUtils;
54 import org.onap.policy.models.decisions.concepts.DecisionRequest;
55 import org.onap.policy.models.decisions.concepts.DecisionResponse;
56 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
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.onap.policy.pdp.xacml.xacmltest.TestUtils;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
66 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
67 public class GuardPdpApplicationTest {
69 private static final Logger LOGGER = LoggerFactory.getLogger(GuardPdpApplicationTest.class);
70 private static Properties properties = new Properties();
71 private static File propertiesFile;
72 private static RestServerParameters clientParams = new RestServerParameters();
73 private static XacmlApplicationServiceProvider service;
74 private static DecisionRequest requestVfCount1;
75 private static DecisionRequest requestVfCount3;
76 private static DecisionRequest requestVfCount6;
77 private static StandardCoder gson = new StandardCoder();
78 private static EntityManager em;
79 private static final String DENY = "Deny";
80 private static final String PERMIT = "Permit";
83 public static final TemporaryFolder policyFolder = new TemporaryFolder();
86 * Copies the xacml.properties and policies files into
87 * temporary folder and loads the service provider saving
88 * instance of provider off for other tests to use.
91 public static void setup() throws Exception {
92 LOGGER.info("Setting up class");
94 // Setup our temporary folder
96 XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
97 propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
98 properties, myCreator);
102 ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
103 ServiceLoader.load(XacmlApplicationServiceProvider.class);
105 // Find the guard service application and save for use in all the tests
107 StringBuilder strDump = new StringBuilder("Loaded applications:" + System.lineSeparator());
108 Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
109 while (iterator.hasNext()) {
110 XacmlApplicationServiceProvider application = iterator.next();
112 // Is it our service?
114 if (application instanceof GuardPdpApplication) {
116 // Should be the first and only one
118 assertThat(service).isNull();
119 service = application;
121 strDump.append(application.applicationName());
122 strDump.append(" supports ");
123 strDump.append(application.supportedPolicyTypes());
124 strDump.append(System.lineSeparator());
126 LOGGER.info("{}", strDump);
128 // Tell it to initialize based on the properties file
129 // we just built for it.
131 service.initialize(propertiesFile.toPath().getParent(), clientParams);
133 // Load Decision Requests
135 requestVfCount1 = gson.decode(
136 TextFileUtils.getTextFileAsString(
137 "src/test/resources/requests/guard.vfCount.1.json"),
138 DecisionRequest.class);
139 requestVfCount3 = gson.decode(
140 TextFileUtils.getTextFileAsString(
141 "src/test/resources/requests/guard.vfCount.3.json"),
142 DecisionRequest.class);
143 requestVfCount6 = gson.decode(
144 TextFileUtils.getTextFileAsString(
145 "src/test/resources/requests/guard.vfCount.6.json"),
146 DecisionRequest.class);
148 // Create EntityManager for manipulating DB
150 String persistenceUnit = CountRecentOperationsPip.ISSUER_NAME + ".persistenceunit";
151 em = Persistence.createEntityManagerFactory(
152 GuardPdpApplicationTest.properties.getProperty(persistenceUnit), properties)
153 .createEntityManager();
157 * Clears the database before each test.
161 public void startClean() throws Exception {
162 em.getTransaction().begin();
163 em.createQuery("DELETE FROM Dbao").executeUpdate();
164 em.getTransaction().commit();
168 * Check that decision matches expectation.
170 * @param expected from the response
171 * @param response received
174 public void checkDecision(String expected, DecisionResponse response) throws CoderException {
175 LOGGER.info("Looking for {} Decision", expected);
176 assertThat(response).isNotNull();
177 assertThat(response.getStatus()).isNotNull();
178 assertThat(response.getStatus()).isEqualTo(expected);
180 // Dump it out as Json
182 LOGGER.info(gson.encode(response));
186 * Request a decision and check that it matches expectation.
188 * @param request to send to Xacml PDP
189 * @param expected from the response
192 public void requestAndCheckDecision(DecisionRequest request, String expected) throws CoderException {
194 // Ask for a decision
196 Pair<DecisionResponse, Response> decision = service.makeDecision(request, null);
200 checkDecision(expected, decision.getKey());
204 public void test1Basics() throws CoderException, IOException {
205 LOGGER.info("**************** Running test1 ****************");
207 // Make sure there's an application name
209 assertThat(service.applicationName()).isNotEmpty();
213 assertThat(service.actionDecisionsSupported().size()).isEqualTo(1);
214 assertThat(service.actionDecisionsSupported()).contains("guard");
216 // Ensure it has the supported policy types and
217 // can support the correct policy types.
219 assertThat(service.supportedPolicyTypes()).isNotEmpty();
220 assertThat(service.supportedPolicyTypes().size()).isEqualTo(4);
221 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
222 "onap.policies.controlloop.guard.FrequencyLimiter", "1.0.0"))).isTrue();
223 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
224 "onap.policies.controlloop.guard.FrequencyLimiter", "1.0.1"))).isFalse();
225 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
226 "onap.policies.controlloop.guard.MinMax", "1.0.0"))).isTrue();
227 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
228 "onap.policies.controlloop.guard.MinMax", "1.0.1"))).isFalse();
229 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
230 "onap.policies.controlloop.guard.Blacklist", "1.0.0"))).isTrue();
231 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
232 "onap.policies.controlloop.guard.Blacklist", "1.0.1"))).isFalse();
233 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
234 "onap.policies.controlloop.guard.coordination.FirstBlocksSecond", "1.0.0"))).isTrue();
235 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
236 "onap.policies.controlloop.guard.coordination.FirstBlocksSecond", "1.0.1"))).isFalse();
237 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier("onap.foo", "1.0.1"))).isFalse();
241 public void test2NoPolicies() throws CoderException {
242 LOGGER.info("**************** Running test2 ****************");
243 requestAndCheckDecision(requestVfCount1,PERMIT);
247 public void test3FrequencyLimiter() throws CoderException, FileNotFoundException, IOException,
248 XacmlApplicationException {
249 LOGGER.info("**************** Running test3 ****************");
251 // Now load the vDNS frequency limiter Policy - make sure
252 // the pdp can support it and have it load
255 TestUtils.loadPolicies("src/test/resources/vDNS.policy.guard.frequency.output.tosca.yaml", service);
257 // Zero recent actions: should get permit
259 requestAndCheckDecision(requestVfCount1,PERMIT);
261 // Add entry into operations history DB
263 insertOperationEvent(requestVfCount1);
265 // Only one recent actions: should get permit
267 requestAndCheckDecision(requestVfCount1,PERMIT);
269 // Add entry into operations history DB
271 insertOperationEvent(requestVfCount1);
273 // Two recent actions, more than specified limit of 2: should get deny
275 requestAndCheckDecision(requestVfCount1,DENY);
279 public void test4MinMax() throws CoderException, FileNotFoundException, IOException, XacmlApplicationException {
280 LOGGER.info("**************** Running test4 ****************");
282 // Now load the vDNS min max Policy - make sure
283 // the pdp can support it and have it load
286 TestUtils.loadPolicies("src/test/resources/vDNS.policy.guard.minmax.output.tosca.yaml", service);
288 // vfcount=1 below min of 2: should get a Deny
290 requestAndCheckDecision(requestVfCount1, DENY);
292 // vfcount=3 between min of 2 and max of 5: should get a Permit
294 requestAndCheckDecision(requestVfCount3, PERMIT);
296 // vfcount=6 above max of 5: should get a Deny
298 requestAndCheckDecision(requestVfCount6,DENY);
300 // Add two entry into operations history DB
302 insertOperationEvent(requestVfCount1);
303 insertOperationEvent(requestVfCount1);
305 // vfcount=3 between min of 2 and max of 5, but 2 recent actions is above frequency limit: should get a Deny
307 requestAndCheckDecision(requestVfCount3, DENY);
309 // vfcount=6 above max of 5: should get a Deny
311 requestAndCheckDecision(requestVfCount6, DENY);
315 public void test5MissingFields() throws FileNotFoundException, IOException, XacmlApplicationException,
317 LOGGER.info("**************** Running test5 ****************");
319 // Most likely we would not get a policy with missing fields passed to
320 // us from the API. But in case that happens, or we decide that some fields
321 // will be optional due to re-working of how the XACML policies are built,
322 // let's add support in for that.
324 TestUtils.loadPolicies("src/test/resources/guard.policy-minmax-missing-fields1.yaml", service);
326 // We can create a DecisionRequest on the fly - no need
327 // to have it in the .json files
329 DecisionRequest request = new DecisionRequest();
330 request.setOnapName("JUnit");
331 request.setOnapComponent("test5MissingFields");
332 request.setRequestId(UUID.randomUUID().toString());
333 request.setAction("guard");
334 Map<String, Object> guard = new HashMap<>();
335 guard.put("actor", "FOO");
336 guard.put("recipe", "bar");
337 guard.put("vfCount", "4");
338 Map<String, Object> resource = new HashMap<>();
339 resource.put("guard", guard);
340 request.setResource(resource);
342 // Ask for a decision - should get permit
344 Pair<DecisionResponse, Response> decision = service.makeDecision(request, null);
345 LOGGER.info("Looking for Permit Decision {}", decision.getKey());
346 assertThat(decision.getKey()).isNotNull();
347 assertThat(decision.getKey().getStatus()).isNotNull();
348 assertThat(decision.getKey().getStatus()).isEqualTo("Permit");
352 guard.put("vfCount", "10");
353 resource.put("guard", guard);
354 request.setResource(resource);
355 decision = service.makeDecision(request, null);
356 LOGGER.info("Looking for Deny Decision {}", decision.getKey());
357 assertThat(decision.getKey()).isNotNull();
358 assertThat(decision.getKey().getStatus()).isNotNull();
359 assertThat(decision.getKey().getStatus()).isEqualTo("Deny");
362 @SuppressWarnings("unchecked")
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 {