2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019-2020 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;
26 import static org.assertj.core.api.Assertions.assertThatCode;
28 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.Iterator;
35 import java.util.List;
37 import java.util.Properties;
38 import java.util.ServiceLoader;
39 import java.util.UUID;
40 import javax.persistence.EntityManager;
41 import javax.persistence.Persistence;
42 import org.apache.commons.lang3.tuple.Pair;
43 import org.junit.AfterClass;
44 import org.junit.Before;
45 import org.junit.BeforeClass;
46 import org.junit.ClassRule;
47 import org.junit.FixMethodOrder;
48 import org.junit.Test;
49 import org.junit.rules.TemporaryFolder;
50 import org.junit.runners.MethodSorters;
51 import org.onap.policy.common.endpoints.parameters.RestServerParameters;
52 import org.onap.policy.common.utils.coder.CoderException;
53 import org.onap.policy.common.utils.coder.StandardCoder;
54 import org.onap.policy.common.utils.resources.TextFileUtils;
55 import org.onap.policy.models.decisions.concepts.DecisionRequest;
56 import org.onap.policy.models.decisions.concepts.DecisionResponse;
57 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
58 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
59 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
60 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
61 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
62 import org.onap.policy.pdp.xacml.application.common.operationshistory.CountRecentOperationsPip;
63 import org.onap.policy.pdp.xacml.application.common.operationshistory.Dbao;
64 import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
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 RestServerParameters clientParams = new RestServerParameters();
75 private static XacmlApplicationServiceProvider service;
76 private static DecisionRequest requestVfCount;
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:" + 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
135 requestVfCount = gson.decode(
136 TextFileUtils.getTextFileAsString(
137 "src/test/resources/requests/guard.vfCount.json"),
138 DecisionRequest.class);
140 // Create EntityManager for manipulating DB
142 String persistenceUnit = CountRecentOperationsPip.ISSUER_NAME + ".persistenceunit";
143 em = Persistence.createEntityManagerFactory(
144 GuardPdpApplicationTest.properties.getProperty(persistenceUnit), properties)
145 .createEntityManager();
149 * Close the entity manager.
152 public static void cleanup() throws Exception {
159 * Clears the database before each test so there are no operations in it.
163 public void startClean() throws Exception {
164 em.getTransaction().begin();
165 em.createQuery("DELETE FROM Dbao").executeUpdate();
166 em.getTransaction().commit();
170 * Check that decision matches expectation.
172 * @param expected from the response
173 * @param response received
176 public void checkDecision(String expected, DecisionResponse response) throws CoderException {
177 LOGGER.info("Looking for {} Decision", expected);
178 assertThat(response).isNotNull();
179 assertThat(response.getStatus()).isNotNull();
180 assertThat(response.getStatus()).isEqualTo(expected);
182 // Dump it out as Json
184 LOGGER.info(gson.encode(response));
188 * Request a decision and check that it matches expectation.
190 * @param request to send to Xacml PDP
191 * @param expected from the response
194 public void requestAndCheckDecision(DecisionRequest request, String expected) throws CoderException {
196 // Ask for a decision
198 Pair<DecisionResponse, Response> decision = service.makeDecision(request, null);
202 checkDecision(expected, decision.getKey());
206 public void test1Basics() throws CoderException, IOException {
207 LOGGER.info("**************** Running test1Basics ****************");
209 // Make sure there's an application name
211 assertThat(service.applicationName()).isNotEmpty();
215 assertThat(service.actionDecisionsSupported().size()).isEqualTo(1);
216 assertThat(service.actionDecisionsSupported()).contains("guard");
218 // Ensure it has the supported policy types and
219 // can support the correct policy types.
221 assertThat(service.supportedPolicyTypes()).isNotEmpty();
222 assertThat(service.supportedPolicyTypes().size()).isEqualTo(4);
223 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
224 "onap.policies.controlloop.guard.common.FrequencyLimiter", "1.0.0"))).isTrue();
225 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
226 "onap.policies.controlloop.guard.common.FrequencyLimiter", "1.0.1"))).isFalse();
227 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
228 "onap.policies.controlloop.guard.common.MinMax", "1.0.0"))).isTrue();
229 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
230 "onap.policies.controlloop.guard.common.MinMax", "1.0.1"))).isFalse();
231 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
232 "onap.policies.controlloop.guard.common.Blacklist", "1.0.0"))).isTrue();
233 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
234 "onap.policies.controlloop.guard.common.Blacklist", "1.0.1"))).isFalse();
235 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
236 "onap.policies.controlloop.guard.coordination.FirstBlocksSecond", "1.0.0"))).isTrue();
237 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
238 "onap.policies.controlloop.guard.coordination.FirstBlocksSecond", "1.0.1"))).isFalse();
239 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier("onap.foo", "1.0.1"))).isFalse();
243 public void test2NoPolicies() throws CoderException {
244 LOGGER.info("**************** Running test2NoPolicies ****************");
245 assertThatCode(() -> requestAndCheckDecision(requestVfCount, PERMIT)).doesNotThrowAnyException();
249 public void test3FrequencyLimiter() throws CoderException, FileNotFoundException, IOException,
250 XacmlApplicationException {
251 LOGGER.info("**************** Running test3FrequencyLimiter ****************");
253 // Now load the vDNS frequency limiter Policy - make sure
254 // the pdp can support it and have it load
257 List<ToscaPolicy> loadedPolicies = TestUtils.loadPolicies(
258 "policies/vDNS.policy.guard.frequencylimiter.input.tosca.yaml", service);
259 assertThat(loadedPolicies).hasSize(1);
260 assertThat(loadedPolicies.get(0).getName()).isEqualTo("guard.frequency.scaleout");
262 // Zero recent actions: should get permit
264 requestAndCheckDecision(requestVfCount, PERMIT);
266 // Add entry into operations history DB
268 insertOperationEvent(requestVfCount);
270 // Two recent actions, more than specified limit of 2: should get deny
272 requestAndCheckDecision(requestVfCount, DENY);
275 @SuppressWarnings("unchecked")
277 public void test4MinMax() throws CoderException, FileNotFoundException, IOException, XacmlApplicationException {
278 LOGGER.info("**************** Running test4MinMax ****************");
280 // Now load the vDNS min max Policy - make sure
281 // the pdp can support it and have it load
284 List<ToscaPolicy> loadedPolicies = TestUtils.loadPolicies(
285 "policies/vDNS.policy.guard.minmaxvnfs.input.tosca.yaml", service);
286 assertThat(loadedPolicies).hasSize(1);
287 assertThat(loadedPolicies.get(0).getName()).isEqualTo("guard.minmax.scaleout");
289 // vfcount=0 below min of 1: should get a Permit
291 requestAndCheckDecision(requestVfCount, PERMIT);
293 // vfcount=1 between min of 1 and max of 2: should get a Permit
295 ((Map<String, Object>) requestVfCount.getResource().get("guard")).put("vfCount", 1);
296 requestAndCheckDecision(requestVfCount, PERMIT);
298 // vfcount=2 hits the max of 2: should get a Deny
300 ((Map<String, Object>) requestVfCount.getResource().get("guard")).put("vfCount", 2);
301 requestAndCheckDecision(requestVfCount, DENY);
303 // vfcount=3 above max of 2: should get a Deny
305 ((Map<String, Object>) requestVfCount.getResource().get("guard")).put("vfCount", 3);
306 requestAndCheckDecision(requestVfCount,DENY);
308 // Insert entry into operations history DB - to indicate a successful
311 insertOperationEvent(requestVfCount);
313 // vfcount=1 between min of 1 and max of 2; MinMax should succeed,
314 // BUT the frequency limiter should fail
316 ((Map<String, Object>) requestVfCount.getResource().get("guard")).put("vfCount", 1);
317 requestAndCheckDecision(requestVfCount, DENY);
320 @SuppressWarnings("unchecked")
322 public void test5Blacklist() throws CoderException, XacmlApplicationException {
323 LOGGER.info("**************** Running test5Blacklist ****************");
325 // Load the blacklist policy in with the others.
327 List<ToscaPolicy> loadedPolicies = TestUtils.loadPolicies(
328 "policies/vDNS.policy.guard.blacklist.input.tosca.yaml", service);
329 assertThat(loadedPolicies).hasSize(1);
330 assertThat(loadedPolicies.get(0).getName()).isEqualTo("guard.blacklist.scaleout");
332 // vfcount=0 below min of 1: should get a Permit because target is NOT blacklisted
334 requestAndCheckDecision(requestVfCount, PERMIT);
336 // vfcount=1 between min of 1 and max of 2: change the
338 ((Map<String, Object>) requestVfCount.getResource().get("guard"))
339 .put("target", "the-vfmodule-where-root-is-true");
341 // vfcount=0 below min of 1: should get a Deny because target IS blacklisted
343 requestAndCheckDecision(requestVfCount, DENY);
346 @SuppressWarnings("unchecked")
347 private void insertOperationEvent(DecisionRequest request) {
349 // Get the properties
351 Map<String, Object> properties = (Map<String, Object>) request.getResource().get("guard");
352 assertThat(properties).isNotNull();
356 Dbao newEntry = new Dbao();
357 newEntry.setActor(properties.get("actor").toString());
358 newEntry.setOperation(properties.get("recipe").toString());
359 newEntry.setClosedLoopName(properties.get("clname").toString());
360 newEntry.setOutcome("SUCCESS");
361 newEntry.setStarttime(Date.from(Instant.now().minusMillis(20000)));
362 newEntry.setEndtime(Date.from(Instant.now()));
363 newEntry.setRequestId(UUID.randomUUID().toString());
364 newEntry.setTarget(properties.get("target").toString());
365 LOGGER.info("Inserting {}", newEntry);
366 em.getTransaction().begin();
367 em.persist(newEntry);
368 em.getTransaction().commit();