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