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