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