2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2021 Nordix Foundation.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
20 * SPDX-License-Identifier: Apache-2.0
21 * ============LICENSE_END=========================================================
24 package org.onap.policy.xacml.pdp.application.guard;
26 import static org.assertj.core.api.Assertions.assertThat;
27 import static org.assertj.core.api.Assertions.assertThatCode;
29 import com.att.research.xacml.api.Response;
31 import java.io.FileNotFoundException;
32 import java.io.IOException;
34 import java.time.Instant;
35 import java.util.Iterator;
36 import java.util.List;
38 import java.util.Properties;
39 import java.util.ServiceLoader;
40 import java.util.UUID;
41 import javax.persistence.EntityManager;
42 import javax.persistence.Persistence;
43 import org.apache.commons.lang3.tuple.Pair;
44 import org.junit.AfterClass;
45 import org.junit.Before;
46 import org.junit.BeforeClass;
47 import org.junit.ClassRule;
48 import org.junit.FixMethodOrder;
49 import org.junit.Test;
50 import org.junit.rules.TemporaryFolder;
51 import org.junit.runners.MethodSorters;
52 import org.onap.policy.common.endpoints.parameters.RestServerParameters;
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.guard.OperationsHistory;
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.ToscaConceptIdentifier;
60 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
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.xacmltest.TestUtils;
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 requestVfCount;
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 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", properties,
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:" + XacmlPolicyUtils.LINE_SEPARATOR);
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(XacmlPolicyUtils.LINE_SEPARATOR);
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
136 gson.decode(TextFileUtils.getTextFileAsString("src/test/resources/requests/guard.vfCount.json"),
137 DecisionRequest.class);
139 // Create EntityManager for manipulating DB
141 String persistenceUnit = CountRecentOperationsPip.ISSUER_NAME + ".persistenceunit";
143 .createEntityManagerFactory(GuardPdpApplicationTest.properties.getProperty(persistenceUnit), properties)
144 .createEntityManager();
148 * Close the entity manager.
151 public static void cleanup() throws Exception {
158 * Clears the database before each test so there are no operations in it.
162 public void startClean() throws Exception {
163 em.getTransaction().begin();
164 em.createQuery("DELETE FROM OperationsHistory").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, null);
201 checkDecision(expected, decision.getKey());
205 public void test1Basics() throws CoderException, IOException {
206 LOGGER.info("**************** Running test1Basics ****************");
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(5);
222 assertThat(service.canSupportPolicyType(
223 new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.FrequencyLimiter", "1.0.0")))
225 assertThat(service.canSupportPolicyType(
226 new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.FrequencyLimiter", "1.0.1")))
228 assertThat(service.canSupportPolicyType(
229 new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.MinMax", "1.0.0"))).isTrue();
230 assertThat(service.canSupportPolicyType(
231 new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.MinMax", "1.0.1"))).isFalse();
232 assertThat(service.canSupportPolicyType(
233 new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.Blacklist", "1.0.0"))).isTrue();
234 assertThat(service.canSupportPolicyType(
235 new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.Blacklist", "1.0.1"))).isFalse();
236 assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
237 "onap.policies.controlloop.guard.coordination.FirstBlocksSecond", "1.0.0"))).isTrue();
238 assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
239 "onap.policies.controlloop.guard.coordination.FirstBlocksSecond", "1.0.1"))).isFalse();
240 assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier("onap.foo", "1.0.1"))).isFalse();
241 assertThat(service.canSupportPolicyType(
242 new ToscaConceptIdentifier("onap.policies.controlloop.guard.common.Filter", "1.0.0"))).isTrue();
246 public void test2NoPolicies() throws CoderException {
247 LOGGER.info("**************** Running test2NoPolicies ****************");
248 assertThatCode(() -> requestAndCheckDecision(requestVfCount, PERMIT)).doesNotThrowAnyException();
252 public void test3FrequencyLimiter()
253 throws CoderException, FileNotFoundException, IOException, XacmlApplicationException {
254 LOGGER.info("**************** Running test3FrequencyLimiter ****************");
256 // Now load the vDNS frequency limiter Policy - make sure
257 // the pdp can support it and have it load
260 List<ToscaPolicy> loadedPolicies =
261 TestUtils.loadPolicies("policies/vDNS.policy.guard.frequencylimiter.input.tosca.yaml", service);
262 assertThat(loadedPolicies).hasSize(1);
263 assertThat(loadedPolicies.get(0).getName()).isEqualTo("guard.frequency.scaleout");
265 // Zero recent actions: should get permit
267 requestAndCheckDecision(requestVfCount, PERMIT);
269 // Add entry into operations history DB
271 insertOperationEvent(requestVfCount);
273 // Two recent actions, more than specified limit of 2: should get deny
275 requestAndCheckDecision(requestVfCount, DENY);
278 @SuppressWarnings("unchecked")
280 public void test4MinMax() throws CoderException, FileNotFoundException, IOException, XacmlApplicationException {
281 LOGGER.info("**************** Running test4MinMax ****************");
283 // Now load the vDNS min max Policy - make sure
284 // the pdp can support it and have it load
287 List<ToscaPolicy> loadedPolicies =
288 TestUtils.loadPolicies("policies/vDNS.policy.guard.minmaxvnfs.input.tosca.yaml", service);
289 assertThat(loadedPolicies).hasSize(1);
290 assertThat(loadedPolicies.get(0).getName()).isEqualTo("guard.minmax.scaleout");
292 // vfcount=0 below min of 1: should get a Permit
294 requestAndCheckDecision(requestVfCount, PERMIT);
296 // vfcount=1 between min of 1 and max of 2: should get a Permit
298 ((Map<String, Object>) requestVfCount.getResource().get("guard")).put("vfCount", 1);
299 requestAndCheckDecision(requestVfCount, PERMIT);
301 // vfcount=2 hits the max of 2: should get a Deny
303 ((Map<String, Object>) requestVfCount.getResource().get("guard")).put("vfCount", 2);
304 requestAndCheckDecision(requestVfCount, DENY);
306 // vfcount=3 above max of 2: should get a Deny
308 ((Map<String, Object>) requestVfCount.getResource().get("guard")).put("vfCount", 3);
309 requestAndCheckDecision(requestVfCount, DENY);
311 // Insert entry into operations history DB - to indicate a successful
314 insertOperationEvent(requestVfCount);
316 // vfcount=1 between min of 1 and max of 2; MinMax should succeed,
317 // BUT the frequency limiter should fail
319 ((Map<String, Object>) requestVfCount.getResource().get("guard")).put("vfCount", 1);
320 requestAndCheckDecision(requestVfCount, DENY);
323 @SuppressWarnings("unchecked")
325 public void test5Blacklist() throws CoderException, XacmlApplicationException {
326 LOGGER.info("**************** Running test5Blacklist ****************");
328 // Load the blacklist policy in with the others.
330 List<ToscaPolicy> loadedPolicies =
331 TestUtils.loadPolicies("policies/vDNS.policy.guard.blacklist.input.tosca.yaml", service);
332 assertThat(loadedPolicies).hasSize(1);
333 assertThat(loadedPolicies.get(0).getName()).isEqualTo("guard.blacklist.scaleout");
335 // vfcount=0 below min of 1: should get a Permit because target is NOT blacklisted
337 requestAndCheckDecision(requestVfCount, PERMIT);
339 // vfcount=1 between min of 1 and max of 2: change the
341 ((Map<String, Object>) requestVfCount.getResource().get("guard")).put("target",
342 "the-vfmodule-where-root-is-true");
344 // vfcount=0 below min of 1: should get a Deny because target IS blacklisted
346 requestAndCheckDecision(requestVfCount, DENY);
348 // vfcount=1 between min of 1 and max of 2: change the
350 ((Map<String, Object>) requestVfCount.getResource().get("guard")).put("target",
351 "another-vfmodule-where-root-is-true");
353 // vfcount=0 below min of 1: should get a Deny because target IS blacklisted
355 requestAndCheckDecision(requestVfCount, DENY);
358 @SuppressWarnings("unchecked")
360 public void test6Filters() throws Exception {
361 LOGGER.info("**************** Running test6Filters ****************");
363 // Re-Load Decision Request - so we can start from scratch
366 gson.decode(TextFileUtils.getTextFileAsString("src/test/resources/requests/guard.vfCount.json"),
367 DecisionRequest.class);
369 // Ensure we are a permit to start
371 requestAndCheckDecision(requestVfCount, PERMIT);
373 // Load the filter policy in with the others.
375 List<ToscaPolicy> loadedPolicies =
376 TestUtils.loadPolicies("src/test/resources/test.policy.guard.filters.yaml", service);
377 assertThat(loadedPolicies).hasSize(2);
379 // Although the region is blacklisted, the id is not
381 requestAndCheckDecision(requestVfCount, PERMIT);
383 // Put in a different vnf id
385 ((Map<String, Object>) requestVfCount.getResource().get("guard")).put("generic-vnf.vnf-id",
386 "different-vnf-id-should-be-denied");
388 // The region is blacklisted, and the id is not allowed
390 requestAndCheckDecision(requestVfCount, DENY);
392 // Let's switch to a different region
394 ((Map<String, Object>) requestVfCount.getResource().get("guard")).put("cloud-region.cloud-region-id",
397 // The region is whitelisted, and the id is also allowed
399 requestAndCheckDecision(requestVfCount, PERMIT);
401 // Put in a blacklisted vnf id
403 ((Map<String, Object>) requestVfCount.getResource().get("guard")).put("generic-vnf.vnf-id",
404 "f17face5-69cb-4c88-9e0b-7426db7edddd");
406 // Although region is whitelisted, the id is blacklisted
408 requestAndCheckDecision(requestVfCount, DENY);
410 // Let's switch to a different region
412 ((Map<String, Object>) requestVfCount.getResource().get("guard")).put("cloud-region.cloud-region-id",
415 // There is no filter for this region, but the id is still blacklisted
417 requestAndCheckDecision(requestVfCount, DENY);
419 // Put in a different vnf id
421 ((Map<String, Object>) requestVfCount.getResource().get("guard")).put("generic-vnf.vnf-id",
422 "different-vnf-id-should-be-permitted");
424 // There is no filter for this region, and the id is not blacklisted
426 requestAndCheckDecision(requestVfCount, PERMIT);
429 @SuppressWarnings("unchecked")
430 private void insertOperationEvent(DecisionRequest request) {
432 // Get the properties
434 Map<String, Object> properties = (Map<String, Object>) request.getResource().get("guard");
435 assertThat(properties).isNotNull();
439 OperationsHistory newEntry = new OperationsHistory();
440 newEntry.setActor(properties.get("actor").toString());
441 newEntry.setOperation(properties.get("operation").toString());
442 newEntry.setClosedLoopName(properties.get("clname").toString());
443 newEntry.setOutcome("SUCCESS");
444 newEntry.setStarttime(Date.from(Instant.now().minusMillis(20000)));
445 newEntry.setEndtime(Date.from(Instant.now()));
446 newEntry.setRequestId(UUID.randomUUID().toString());
447 newEntry.setTarget(properties.get("target").toString());
448 LOGGER.info("Inserting {}", newEntry);
449 em.getTransaction().begin();
450 em.persist(newEntry);
451 em.getTransaction().commit();