XACML PDP DmaaP Deploy/UnDeploy Function
[policy/xacml-pdp.git] / applications / guard / src / test / java / org / onap / policy / xacml / pdp / application / guard / GuardPdpApplicationTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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.
18  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.xacml.pdp.application.guard;
24
25 import static org.assertj.core.api.Assertions.assertThat;
26
27 import java.io.File;
28 import java.io.FileNotFoundException;
29 import java.io.IOException;
30 import java.sql.Date;
31 import java.time.Instant;
32 import java.util.HashMap;
33 import java.util.Iterator;
34 import java.util.Map;
35 import java.util.Properties;
36 import java.util.ServiceLoader;
37 import java.util.UUID;
38
39 import javax.persistence.EntityManager;
40 import javax.persistence.Persistence;
41
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.utils.coder.CoderException;
51 import org.onap.policy.common.utils.coder.StandardCoder;
52 import org.onap.policy.common.utils.resources.TextFileUtils;
53 import org.onap.policy.models.decisions.concepts.DecisionRequest;
54 import org.onap.policy.models.decisions.concepts.DecisionResponse;
55 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
56 import org.onap.policy.pdp.xacml.application.common.OnapOperationsHistoryDbao;
57 import org.onap.policy.pdp.xacml.application.common.TestUtils;
58 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
59 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
60 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
63
64 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
65 public class GuardPdpApplicationTest {
66
67     private static final Logger LOGGER = LoggerFactory.getLogger(GuardPdpApplicationTest.class);
68     private static Properties properties = new Properties();
69     private static File propertiesFile;
70     private static XacmlApplicationServiceProvider service;
71     private static DecisionRequest requestVfCount1;
72     private static DecisionRequest requestVfCount3;
73     private static DecisionRequest requestVfCount6;
74     private static StandardCoder gson = new StandardCoder();
75     private static EntityManager em;
76     private static final String DENY = "Deny";
77     private static final String PERMIT = "Permit";
78
79     @ClassRule
80     public static final TemporaryFolder policyFolder = new TemporaryFolder();
81
82     /**
83      * Copies the xacml.properties and policies files into
84      * temporary folder and loads the service provider saving
85      * instance of provider off for other tests to use.
86      */
87     @BeforeClass
88     public static void setUp() throws Exception {
89         LOGGER.info("Setting up class");
90         //
91         // Setup our temporary folder
92         //
93         XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
94         propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
95                 properties, myCreator);
96         //
97         // Load service
98         //
99         ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
100                 ServiceLoader.load(XacmlApplicationServiceProvider.class);
101         //
102         // Find the guard service application and save for use in all the tests
103         //
104         StringBuilder strDump = new StringBuilder("Loaded applications:" + System.lineSeparator());
105         Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
106         while (iterator.hasNext()) {
107             XacmlApplicationServiceProvider application = iterator.next();
108             //
109             // Is it our service?
110             //
111             if (application instanceof GuardPdpApplication) {
112                 //
113                 // Should be the first and only one
114                 //
115                 assertThat(service).isNull();
116                 service = application;
117             }
118             strDump.append(application.applicationName());
119             strDump.append(" supports ");
120             strDump.append(application.supportedPolicyTypes());
121             strDump.append(System.lineSeparator());
122         }
123         LOGGER.info("{}", strDump);
124         //
125         // Tell it to initialize based on the properties file
126         // we just built for it.
127         //
128         service.initialize(propertiesFile.toPath().getParent());
129         //
130         // Load Decision Requests
131         //
132         requestVfCount1 = gson.decode(
133                 TextFileUtils.getTextFileAsString(
134                     "../../main/src/test/resources/decisions/decision.guard.vfCount.1.input.json"),
135                     DecisionRequest.class);
136         requestVfCount3 = gson.decode(
137                 TextFileUtils.getTextFileAsString(
138                     "../../main/src/test/resources/decisions/decision.guard.vfCount.3.input.json"),
139                     DecisionRequest.class);
140         requestVfCount6 = gson.decode(
141                 TextFileUtils.getTextFileAsString(
142                     "../../main/src/test/resources/decisions/decision.guard.vfCount.6.input.json"),
143                     DecisionRequest.class);
144         //
145         // Create EntityManager for manipulating DB
146         //
147         em = Persistence.createEntityManagerFactory(
148                 GuardPdpApplicationTest.properties.getProperty("historydb.persistenceunit"), properties)
149                 .createEntityManager();
150     }
151
152     /**
153      * Clears the database before each test.
154      *
155      */
156     @Before
157     public void startClean() throws Exception {
158         em.getTransaction().begin();
159         em.createQuery("DELETE FROM OnapOperationsHistoryDbao").executeUpdate();
160         em.getTransaction().commit();
161     }
162
163     /**
164      * Check that decision matches expectation.
165      *
166      * @param expected from the response
167      * @param response received
168      *
169      **/
170     public void checkDecision(String expected, DecisionResponse response) throws CoderException {
171         LOGGER.info("Looking for {} Decision", expected);
172         assertThat(response).isNotNull();
173         assertThat(response.getStatus()).isNotNull();
174         assertThat(response.getStatus()).isEqualTo(expected);
175         //
176         // Dump it out as Json
177         //
178         LOGGER.info(gson.encode(response));
179     }
180
181     /**
182      * Request a decision and check that it matches expectation.
183      *
184      * @param request to send to Xacml PDP
185      * @param expected from the response
186      *
187      **/
188     public void requestAndCheckDecision(DecisionRequest request, String expected) throws CoderException {
189         //
190         // Ask for a decision
191         //
192         DecisionResponse response = service.makeDecision(request);
193         //
194         // Check decision
195         //
196         checkDecision(expected, response);
197     }
198
199     @Test
200     public void test1Basics() throws CoderException, IOException {
201         LOGGER.info("**************** Running test1 ****************");
202         //
203         // Make sure there's an application name
204         //
205         assertThat(service.applicationName()).isNotEmpty();
206         //
207         // Decisions
208         //
209         assertThat(service.actionDecisionsSupported().size()).isEqualTo(1);
210         assertThat(service.actionDecisionsSupported()).contains("guard");
211         //
212         // Ensure it has the supported policy types and
213         // can support the correct policy types.
214         //
215         assertThat(service.supportedPolicyTypes()).isNotEmpty();
216         assertThat(service.supportedPolicyTypes().size()).isEqualTo(2);
217         assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
218                 "onap.policies.controlloop.guard.FrequencyLimiter", "1.0.0"))).isTrue();
219         assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
220                 "onap.policies.controlloop.guard.FrequencyLimiter", "1.0.1"))).isFalse();
221         assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
222                 "onap.policies.controlloop.guard.MinMax", "1.0.0"))).isTrue();
223         assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
224                 "onap.policies.controlloop.guard.MinMax", "1.0.1"))).isFalse();
225         assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier("onap.foo", "1.0.1"))).isFalse();
226     }
227
228     @Test
229     public void test2NoPolicies() throws CoderException {
230         LOGGER.info("**************** Running test2 ****************");
231         requestAndCheckDecision(requestVfCount1,PERMIT);
232     }
233
234     @Test
235     public void test3FrequencyLimiter() throws CoderException, FileNotFoundException, IOException,
236         XacmlApplicationException {
237         LOGGER.info("**************** Running test3 ****************");
238         //
239         // Now load the vDNS frequency limiter Policy - make sure
240         // the pdp can support it and have it load
241         // into the PDP.
242         //
243         TestUtils.loadPolicies("src/test/resources/vDNS.policy.guard.frequency.output.tosca.yaml", service);
244         //
245         // Zero recent actions: should get permit
246         //
247         requestAndCheckDecision(requestVfCount1,PERMIT);
248         //
249         // Add entry into operations history DB
250         //
251         insertOperationEvent(requestVfCount1);
252         //
253         // Only one recent actions: should get permit
254         //
255         requestAndCheckDecision(requestVfCount1,PERMIT);
256         //
257         // Add entry into operations history DB
258         //
259         insertOperationEvent(requestVfCount1);
260         //
261         // Two recent actions, more than specified limit of 2: should get deny
262         //
263         requestAndCheckDecision(requestVfCount1,DENY);
264     }
265
266     @Test
267     public void test4MinMax() throws CoderException, FileNotFoundException, IOException, XacmlApplicationException {
268         LOGGER.info("**************** Running test4 ****************");
269         //
270         // Now load the vDNS min max Policy - make sure
271         // the pdp can support it and have it load
272         // into the PDP.
273         //
274         TestUtils.loadPolicies("src/test/resources/vDNS.policy.guard.minmax.output.tosca.yaml", service);
275         //
276         // vfcount=1 below min of 2: should get a Deny
277         //
278         requestAndCheckDecision(requestVfCount1, DENY);
279         //
280         // vfcount=3 between min of 2 and max of 5: should get a Permit
281         //
282         requestAndCheckDecision(requestVfCount3, PERMIT);
283         //
284         // vfcount=6 above max of 5: should get a Deny
285         //
286         requestAndCheckDecision(requestVfCount6,DENY);
287         //
288         // Add two entry into operations history DB
289         //
290         insertOperationEvent(requestVfCount1);
291         insertOperationEvent(requestVfCount1);
292         //
293         // vfcount=3 between min of 2 and max of 5, but 2 recent actions is above frequency limit: should get a Deny
294         //
295         requestAndCheckDecision(requestVfCount3, DENY);
296         //
297         // vfcount=6 above max of 5: should get a Deny
298         //
299         requestAndCheckDecision(requestVfCount6, DENY);
300     }
301
302     @Test
303     public void test5MissingFields() throws FileNotFoundException, IOException, XacmlApplicationException,
304         CoderException {
305         LOGGER.info("**************** Running test5 ****************");
306         //
307         // Most likely we would not get a policy with missing fields passed to
308         // us from the API. But in case that happens, or we decide that some fields
309         // will be optional due to re-working of how the XACML policies are built,
310         // let's add support in for that.
311         //
312         TestUtils.loadPolicies("src/test/resources/guard.policy-minmax-missing-fields1.yaml", service);
313         //
314         // We can create a DecisionRequest on the fly - no need
315         // to have it in the .json files
316         //
317         DecisionRequest request = new DecisionRequest();
318         request.setOnapName("JUnit");
319         request.setOnapComponent("test5MissingFields");
320         request.setRequestId(UUID.randomUUID().toString());
321         request.setAction("guard");
322         Map<String, Object> guard = new HashMap<>();
323         guard.put("actor", "FOO");
324         guard.put("recipe", "bar");
325         guard.put("vfCount", "4");
326         Map<String, Object> resource = new HashMap<>();
327         resource.put("guard", guard);
328         request.setResource(resource);
329         //
330         // Ask for a decision - should get permit
331         //
332         DecisionResponse response = service.makeDecision(request);
333         LOGGER.info("Looking for Permit Decision {}", response);
334         assertThat(response).isNotNull();
335         assertThat(response.getStatus()).isNotNull();
336         assertThat(response.getStatus()).isEqualTo("Permit");
337         //
338         // Try a deny
339         //
340         guard.put("vfCount", "10");
341         resource.put("guard", guard);
342         request.setResource(resource);
343         response = service.makeDecision(request);
344         LOGGER.info("Looking for Deny Decision {}", response);
345         assertThat(response).isNotNull();
346         assertThat(response.getStatus()).isNotNull();
347         assertThat(response.getStatus()).isEqualTo("Deny");
348     }
349
350     @SuppressWarnings("unchecked")
351     private void insertOperationEvent(DecisionRequest request) {
352         //
353         // Get the properties
354         //
355         Map<String, Object> properties = (Map<String, Object>) request.getResource().get("guard");
356         assertThat(properties).isNotNull();
357         //
358         // Add an entry
359         //
360         OnapOperationsHistoryDbao newEntry = new OnapOperationsHistoryDbao();
361         newEntry.setActor(properties.get("actor").toString());
362         newEntry.setOperation(properties.get("recipe").toString());
363         newEntry.setClName(properties.get("clname").toString());
364         newEntry.setOutcome("SUCCESS");
365         newEntry.setStarttime(Date.from(Instant.now().minusMillis(20000)));
366         newEntry.setEndtime(Date.from(Instant.now()));
367         newEntry.setRequestId(UUID.randomUUID().toString());
368         newEntry.setTarget(properties.get("target").toString());
369         LOGGER.info("Inserting {}", newEntry);
370         em.getTransaction().begin();
371         em.persist(newEntry);
372         em.getTransaction().commit();
373     }
374
375     @AfterClass
376     public static void cleanup() throws Exception {
377         em.close();
378     }
379 }